Module: HstoreAttributeSupport::Base::ClassMethods

Defined in:
lib/hstore_attribute_support/base.rb

Instance Method Summary collapse

Instance Method Details

#hstore_attr_accessor(attribute_name, hstore_column, options = {}) ⇒ Object

this class method allows descendant classes to set up attributes, which are stored in a hstore column. this solves two problems:

  1. by providing a cast hint, it will take care of the data type, which is lost by the hstore and was a pure string otherwise

  2. it provides an easy way to set up defaults, as rails AR mechanism fail here (no database defaults available for virtual attributes)



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/hstore_attribute_support/base.rb', line 60

def hstore_attr_accessor(attribute_name, hstore_column, options = {})
  options = {
    :cast    => nil,
    :default => nil
  }.merge(options).with_indifferent_access

  self.hstore_attributes ||= {}

  self.hstore_attributes[attribute_name.to_s] = {
    :column  => hstore_column.to_s,
    :cast    => options[:cast],
    :default => options[:default]
  }

  class_eval %Q{
    def #{attribute_name}
      return read_hstore_attribute("#{attribute_name}")
    end

    def #{attribute_name}?
      return read_hstore_attribute("#{attribute_name}").present?
    end

    def #{attribute_name}=(value)
      return write_hstore_attribute("#{attribute_name}", value)
    end
  }
end