Module: HstoreAttributeSupport::Base::InstanceMethods

Defined in:
lib/hstore_attribute_support/base.rb

Instance Method Summary collapse

Instance Method Details

#read_hstore_attribute(attribute_name) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/hstore_attribute_support/base.rb', line 92

def read_hstore_attribute(attribute_name)
  ha_column   = self.class.hstore_attributes[attribute_name][:column]
  ha_cast     = self.class.hstore_attributes[attribute_name][:cast]
  hstore_data = self.send(:"#{ha_column}").try(:with_indifferent_access)

  return nil unless hstore_data

  value = hstore_data[attribute_name]

  return value unless ha_cast

  case ha_cast
  when :integer
    return value.to_i
  when :float
    return value.to_f
  when :decimal
    return value.to_s.to_d
  when :boolean
    return !(value.to_s == '' || value.to_s == 'false')
  when :bool
    return !(value.to_s == '' || value.to_s == 'false')
  when :string
    return value.to_s
  when :datetime
    return value.to_s.to_datetime
  when :date
    return value.to_s.to_date
  else
  end

  return ha_cast.call(value) if ha_cast.is_a?(Proc)

  raise "read_hstore_attribute failed when trying to cast the type \"#{ha_cast.inspect}\". Please define the type as one of [:integer, :float, :decimal, :boolean, :string, :datetime, :date] or pass in a lambda with one parameter to perform custom casts."
end

#write_hstore_attribute(attribute_name, value) ⇒ Object



128
129
130
131
132
133
134
# File 'lib/hstore_attribute_support/base.rb', line 128

def write_hstore_attribute(attribute_name, value)
  ha_column   = self.class.hstore_attributes[attribute_name][:column]
  hstore_data = (self.send(:"#{ha_column}") || {}).with_indifferent_access
  hstore_data = hstore_data.merge({attribute_name => value})
  self.send(:"#{ha_column}=", hstore_data)
  self
end