Giter Site home page Giter Site logo

leafy's Introduction

Leafy Build Status Maintainability Test Coverage

A toolkit for dynamic custom attributes for Ruby applications.

  • Simple modular design - load only things you need
  • Stored as JSON with your models - allows you to avoid expensive JOIN queries (supports postgresql json/jsonb data types)
  • Type inference - Infers type from custom field data
  • Add your own custom field types

Supported data types:

  • string - strings
  • integer - integer numbers
  • double - floating point numbers
  • datetime - Time instances
  • date - Date instances
  • bool - TrueClass and FalseClass instances

Quick start

Add Leafy to Gemfile

gem 'leafy-ruby'

Plain Ruby app

Include "Plain old ruby object" mixin into your class definition to start using leafy

class SchemaHost < ActiveRecord::Base
  include Leafy::Mixin::Schema[:poro]

  attr_accessor :leafy_data
end

class FieldsHost < ActiveRecord::Base
  include Leafy::Mixin::Fields[:poro]

  attr_accessor :leafy_data
  attr_accessor :leafy_fields
end

Schema mixin introduces next methods:

  • #leafy_fields (Schema) returns Schema instance allowing you to iterate through custom attribute definitions.
  • #leafy_fields= schema setter method
  • #leafy_fields_attributes= nested attributes setter method

Fields mixin:

  • #leafy_values (Hash) returns a hash representation of your fields data
  • #leafy_values= allows you to assign custom attributes data
  • #leafy_fields_values (Leafy::FieldValueCollection) returns a collection of Field::Value instances which provide more control over values data

Please note: Leafy is stateless and changing Schema instance won't reflect on your active record model instance. For changes to take place you have to explicitly assign schema or attributes data to the model.

host = SchemaHost.new
host.leafy_fields_attributes = [
  { name: "Field 1", type: :integer, id: "id_1", metadata: { default: 1, placeholder: "enter an integer", required: true } },
  { name: "Field 2", type: :string, id: "id_2", metadata: { default: "", placeholder: "enter value" } },
  { name: "Field 3", type: :datetime, id: "id_3", metadata: { order: 10000 } }
]

# or build schema yourself

field_1 = Leafy::Field.new(name: "Field 1", type: :integer, id: "id_1", metadata: { default: 1, placeholder: "enter an integer", required: true })
field_2 = Leafy::Field.new(name: "Field 2", type: :string, id: "id_2", metadata: { default: "", placeholder: "enter value" })
field_3 = Leafy::Field.new(name: "Field 3", type: :datetime, id: "id_3", metadata: { order: 10000 })

schema = Leafy::Schema.new
schema << field_1
schema << field_2
schema << field_3

host.leafy_fields = schema

# after that reference schema for fields target instance

target = FieldsHost.new
target.leafy_fields = host.leafy_fields
target.leafy_values

# => { "id_1" => nil, "id_2" => nil, "id_3" => nil }

target.leafy_values = { "id_1": 123, "id_2": "test", "id_3": Time.new(2018,10,10, 10,10,10, "+03:00"), "junk": "some junk data" }
target.leafy_values

# => { "id_1": 123, "id_2": "test", "id_3": Time.new(2018,10,10, 10,10,10, "+03:00") }

ActiveRecord

Add migration

add_column :schema_hosts, :leafy_data, :text, null: false, default: "{}"
add_column :fields_hosts, :leafy_data, :text, null: false, default: "{}"
# for postgresql
# add_column :leafy_data, :jsonb, null: false, default: {}

Update your models

class SchemaHost < ActiveRecord::Base
  include Leafy::Mixin::Schema[:active_record]
end

class FieldsHost < ActiveRecord::Base
  include Leafy::Mixin::Fields[:active_record]

  belongs_to :schema_host, required: true
  delegate :leafy_fields, to: :schema_host
end
host = SchemaHost.create(
  leafy_fields_attributes: [
    { name: "Field 1", type: :integer, id: "id_1", metadata: { default: 1, placeholder: "enter an integer", required: true } },
    { name: "Field 2", type: :string, id: "id_2", metadata: { default: "", placeholder: "enter value" } },
    { name: "Field 3", type: :datetime, id: "id_3", metadata: { order: 10000 } }
  ]
)

target = FieldsHost.create(schema_host: host)
target.leafy_values

# => { "id_1" => nil, "id_2" => nil, "id_3" => nil }

target.leafy_values = { "id_1": 123, "id_2": "test", "id_3": Time.new(2018,10,10, 10,10,10, "+03:00"), "junk": "some junk data" }
target.save!
target.reload

target.leafy_values

# => { "id_1": 123, "id_2": "test", "id_3": Time.new(2018,10,10, 10,10,10, "+03:00") }

Configuration

In you initialization code

If you get a NameError: uninitialized constant in Rails, please ensure you have required leafy in an initializer.

in app/config/initializers/leafy.rb simply add require 'leafy'

class MyLovelyCoder
  def dump(data)
    "lovely_#{data}"
  end

  def load(data)
    data.split("_")[1]
  end
end

Leafy.configure do |config|
  # you may wonna use oj instead
  config.coder = MyLovelyCoder.new
end

Adding your own types

Leafy allows adding your own data types To allow leafy process your own data type you need to describe how to store it. For that purpose leafy utilizes converter classes associated for each type.

Converter instance has to implement #dump and #load methods

class MyComplexTypeConverter
  def self.load(json_string)
    #  parsing logic
    return MyComplexType.new(parsed_data)
  end

  def self.dump(my_complex_type_instance)
    # serializing logic
    return json
  end
end

Leafy.register_converter(:complex_type, MyComplexTypeConverter)

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/estepnv/leafy.

License

The gem is available as open source under the terms of the MIT License.

leafy's People

Contributors

estepnv avatar sqlninja avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

shushpan sqlninja

leafy's Issues

Avoid dumping and parsing JSON for jsonb field

We use Leafy with ActiveRecord and Postgres. Our leafy_data type is jsonb. leafy_fields and leafy_values work fine.

But sometimes we need to use data from leafy_data field directly in SQL queries. Because of serialization to JSON text before saving to the database Postgres thinks it is a string and can't parse it or convert to JSON type. So the problem is that we can't use leafy_data in SQL queries.

I think, one of the possible solutions is to modify FieldValueCollection dump and load to not use json serialization for ActiveRecord json/jsonb type fields. What do you think about this?

Leafy::FieldValueCollection

def self.dump(field_values_collection, json_serialization = true)
  collection = field_values_collection
                 .map { |field_value| [field_value.id, field_value.raw] }
                 .to_h

  json_serialization ? JSON.dump(collection) : collection
end

def self.load(leafy_fields, data, json_serialization = true)
  Leafy::FieldValueCollection.new(
      leafy_fields,
      json_serialization ? JSON.load(data) : data
  )
end

And call it like that:

Leafy::Mixin::ActiveRecord::Fields::InstanceMethods

def leafy_field_values
  :Leafy::FieldValueCollection.load(leafy_fields, leafy_data || "{}", activerecord_json_column?)
end

Unable to update values

Using Rails 6, ActiveRecord, and Postgres

After retrieving an existing model from the database, I updated the model to have a "custom" field:

tc.update(
  leafy_fields_attributes: [
    { name: "hs_city", type: :string}
    ]  
) 

Although, upon trying to pull the values (which I'd expect to be nil) I get an undefined method 'leafy_values' error. So no getter...
So I thought perhaps I had to assign values (even though that shouldn't be the case)

tc.leafy_values ={ "hs_city": 'Gallatin'}

But this threw basically the same error undefined method 'leafy_values=' so no setter...

But indeed the object did store the "custom" field:

tc.leafy_fields
=> #<Leafy::Schema:0x00007fcc0875f400 @fields=[#<Leafy::Field:0x00007fcc0875f3b0 @id="hs_city-eed709f9-fea3-47ad-97e1-5e81ef800a66", @metadata={}, @name="hs_city", @type="string">]>

Am I missing something from the Read me? Or perhaps another initializer/config?

Uninitialized constant

Any reason I'd be seeing this in my rails 6 app?
NameError: uninitialized constant #<Class:0x00007ff1e9c351f8>::Leafy

My Model has this:

class TeamContact < ApplicationRecord
  include Leafy::Mixin::Schema[:active_record]
 ...
end

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.