Using Rails 5 attributes api with hash virtual attributes - ruby-on-rails

I have a hash store as follows:
store :order_details, accessors: %w{item_name, external_id, total......etc}, coder: JSON
I'm deserializing this to a ruby object using a lib class elsewhere with a couple of methods in it for validations/operations
I would like to make use of the rails 5 attributes api instead so that I could directly have:
attribute :order_details, Type::OrderDetailType.new
(plus it would make it easier to add validations to each field in my hash)
I've seen examples online for using rails5's attributes api for simple virtual attributes(strings, integers...etc), but have not come across any info on how to implement it for a hash attribute.
Would appreciate it if someone could point me in the right direction.

Extend Type::OrderDetailType from ActiveRecord::Type::Value
You can override cast and serialize method.
def cast(value)
value
end
def serialize(value)
value
end
An example of Money type:
# app/models/product.rb
class Product < ApplicationRecord
attribute :price_in_cents, MoneyType.new
end
class MoneyType < ActiveRecord::Type::Integer
def type_cast(value)
# convert values like '$10.00' to 1000
end
end
product = Product.new(price_in_cents: '$10.00')
product.price_in_cents #=> 1000
Doc: http://edgeapi.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html
Example: http://nithinbekal.com/posts/rails-5-features/

Related

How to add a virtual attribute to a model in Ruby on Rails?

I'm working on a RubyonRails/ActiveAdmin application. My RoR version is 4.2.5 and AA version is 1.0.0. I have a model Message as follows.
class Message < ActiveRecord::Base
belongs_to :user
validates :user, :content, presence: true
def palindrome
# return true/false
end
end
As you see, I want to have a read-only attribute palindrome which only depends on the content of message. I want this attribute to be treated exactly like a normal attribute. By normal, I mean when I retrieve messages via rails console or request json format of messages, I want to see a palindrome attribute in the list. I would also like to have a filter for message by this attribute.
I'm not sure how could I achieve this.
Ruby actually lets you create virtual attributes this way, which keeps you from having to manually create getter and setter methods:
attr_reader :palindrome #getter
attr_writer :palindrome #setter
attr_accessor :palindrome #both
You can also pass multiple arguments too:
attr_accessor :palindrome, :foo, :bar
The documentation for it isn't the greatest.
In your model, you can write attribute accessors (reader/writer) for your virtual attribute palindrome attribute this way:
# attr_reader
def palindrome
self[:palindrome]
end
# attr_writer
def palindrome=(val)
self[:palindrome] = val
end
# virtual attribute
def palindrome
#return true/false
end
And, as you are using Rails 4, you have to whitelist palindrome attribute like any other model attribute in your strong param definition inside your controller in order to able to mass assign the value of palindrome. Something like this:
# your_controller.rb
private
def your_model_params
params.require(:message).permit(:palindrome)
end
Take a look at this RailsCast on Virtual Attributes. Although, it's a bit old, but would be useful for concepts.
Note:
A virtual attribute will not show up in the param list automatically. But, you should be able to access it via Rails console like this: Message.new.palindrome. Also, you can expose this virtual attribute in your JSON API, for example if you are using Active Model Serializer, you can have: attribute palindrome in your MessageSerializer and then palindrome will be exposed to the JSON API.
Since Rails 5 you can also set virtual attributes like this:
attribute :palindrome, :boolean
It automatically casts the attribute to the specified type, which can be useful when the value comes from forms. This GoRails video shows some really good examples of both using the attr_accessor and the attribute approach. The documentation also includes some examples.

Rails model -- non persistent class member or property?

Is it possible / advisable to have a member of a class that is not persisted to the database for a rails model?
I want to store the last type the user selects in a session variable. Since I cant set the session variable from my model, I want to store the value in a "dummy" class member that just passes the value back to the controller.
Can you have such a class member?
Adding non-persisted attributes to a Rails model is just like any other Ruby class:
class User < ActiveRecord::Base
attr_accessor :someattr
end
me = User.new(name: 'Max', someattr: 'bar')
me.someattr # "bar"
me.someattr = 'foo'
The extended explanation:
In Ruby all instance variables are private and do not need to be defined before assignment.
attr_accessor creates a setter and getter method:
class User < ActiveRecord::Base
def someattr
#someattr
end
def someattr=(value)
#someattr = value
end
end
There is one special thing going on here; Rails takes the hash you pass to User.new and maps the values to attributes. You could simulate this behavior in a plain ruby class with something like:
class Foo
attr_accessor :bar
def initialize(hash)
hash.keys.each do |key|
setter = "#{key}=".intern
self.send(setter, hash[key]) if self.respond_to? setter
end
end
end
> Foo.new(bar: 'baz')
=> <Foo:0x0000010112aa50 #bar="baz">
Classes in Ruby can also be re-opened at any point, ActiveRecord uses this ability to "auto-magically" add getters and setters to your models based on its database columns (ActiveRecord figures out which attributes to add based on the database schema).
Yes you can, the code below allows you to set my_class_variable and inside the model reference it as #my_class_variable
class MyCLass < ActiveRecord::Base
attr_accessor :my_class_variable
def do_something_with_it
#my_class_variable + 10
end

Making virtual attributes be part of one Hash

I have a model which has one actual column in the database. This column is stored as a JSON string of configuration. I use a bunch of virtual attributes which I want to map inside of this configuration JSON attribute. I basically dont want to create a bunch columns in the db, but rather use this one JSON attribute to contain everything. Is there a cleaner way than the below defs of achieving this?
class Device < ActiveRecord::Base
attr_accessible :configuration
serialize :configuration, JSON
attr_accessor :background_color, :title
# below is ew
def background_color; self.configuration["background_color"]; end
def background_color=(value); self.configuration["background_color"] = value; end
def title; self.configuration["title"]; end
def title=(value); self.configuration["title"] = value; end
end
Ideally i'd be looking for something like attr_maps_to_hash :configuration, [:background_color, :title]. Does something like this exist?
You can use ActiveRecord::Store for this.
class User < ActiveRecord::Base
store :settings, accessors: [ :color, :homepage ]
end
u = User.new(color: 'black', homepage: '37signals.com')
u.color # Accessor stored attribute
u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
# Add additional accessors to an existing store through store_accessor
class SuperUser < User
store_accessor :settings, :privileges, :servants
end
If you are using PostgreSQL, check out HStore.
Rails as of 3.2 has key-value stores built into ActiveRecord-see here:
Where can i read more about Rails 3.2's Data Store with key-value in textfield?
in your case you can have a text field named configuration and then do this:
class Device < AR::Base
store :configuration, accessors: [:title, :background_color, ...]
...
This should work fine with forms, etc..
Two methods come to mind.
First, you could have an array of your attributes [:background_color, :title] and then iterate over them while calling define_method. You would defined two methods, define(method_name) and define("#{method_name}=").
Second, a similar idea but using method missing.
def method_missing(method_name, *args, &block)
...see if it's a get or set...
...do your stuff...
...rain dance...
...yay...
end

Custom serialization for fields in Rails

Is there a way to have a custom serialization for fields in rails, a method that runs when a field is saved and loaded to convert from/to a string which is what ultimately is saved on the database.
Specifically what I want to do is have a field of type symbol like gender, with possible values :male and :female storing "male" and "female" on the database. There are some workarounds, like:
def gender
read_attribute(:gender).try(:to_sym)
end
but that leaves obj.attributes unchanged, so it's a leaky abstraction.
You can do it in Rails 3.1. The object you want to serialize has to reply to load and dump methods.
Here is an example of serializing a string in Base64.
class User < ActiveRecord::Base
class Base64
def load(text)
return unless text
text.unpack('m').first
end
def dump(text)
[text].pack 'm'
end
end
serialize :bank_account_number, Base64.new
end
For more details see: http://archives.edgerails.info/articles/what-s-new-in-edge-rails/2011/03/09/custom-activerecord-attribute-serialization/index.html
def whachamacallit
read_attribute("whachamacallit").to_sym
end
def whachamacallit=(name)
write_attribute("whachamacallit", name.to_s)
end
store them as stings in the database, but extract them as symbols when you pull them out then convert back before you save.
would work with any number or combination of strings / symbols.
to limit it to only a select few
validates_inclusion_of :whachamacallit, :in => [ :male, :female, :unknown, :hidden ]
From http://blog.quov.is/2012/05/01/custom-activerecord-attribute-serializers/
class Recipe < ActiveRecord::Base
serialize :ingredients, IngredientsList
end
class IngredientsList < Array
def self.dump(ingredients)
ingredients ? ingredients.join("\n") : nil
end
def self.load(ingredients)
ingredients ? new(ingredients.split("\n")) : nil
end
end
you can define the models to_xml for a model and it will do that
http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html
its possible to define Marshall.dump and put in that way i think, but its something to look into
You could use serialize method inside the model. Please reference to this link:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html
(ps. search keyword "serialize" in that page ;D)
In short, you could do this:
class YourModel < ActiveRecord::Base
serialize :db_field
end
Rails would automatically serialize the field before saving to database, and deserialize it after fetched from the database.
well for just male/female you could just do a Boolean column like male and if it was false assume that meant female, add wrapper methods for it
def female?
return !self.male?
end
We just released a gem (AttributeHelpers) that does exactly this. Disclaimer: I am a maintainer for the gem.
It allows you to call attr_symbol :gender in your class definition and the serialization happens automagically.

Why won't Rails deserialize my field?

I am using the Classifier:Bayes as part of a model class. I have the class set up to serialize the classifier to the db.
class Foo < ActiveRecord::Base
serialize :classifier
end
The yaml appears in the db just fine after doing some training and saving the object.
But when I query for the class, instance.classifier is a string
#f = Foo.find(params[:id])
#f.classifier.class # is String
I was under the impression that Rails / ActiveRecord would magically deserialize my classifier for me. Is there some setting I need to tweak or am I misunderstanding something?
In the past, I've had to add the class name to the method args...
class Foo < ActiveRecord::Base
serialize :classifier, Classifier::Bayes
end

Resources