Module: HstoreColumns::ClassMethods

Defined in:
lib/hstore-attributes/hstore_columns.rb

Instance Method Summary collapse

Instance Method Details

#hstore(store_attribute, options = {}) ⇒ Object



33
34
35
36
37
38
# File 'lib/hstore-attributes/hstore_columns.rb', line 33

def hstore(store_attribute, options = {})
  accessors = options[:accessors]
  accessors.each do |key, value|
    hstore_accessor store_attribute, key, value.nil? ? :string : value
  end
end

#hstore_accessor(hstore_column, attr_name, type = :string) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/hstore-attributes/hstore_columns.rb', line 23

def hstore_accessor(hstore_column, attr_name, type = :string)
  return unless table_exists?
  access_code                 = "(v=read_hstore('#{attr_name}', '#{hstore_column}')) && #{type_cast_code('v', type)}"

  class_eval <<-RUBY, __FILE__, __LINE__ + 1
        def #{attr_name}; #{access_code}; end
        def #{attr_name}= value; write_hstore('#{attr_name}', value, '#{hstore_column}'); end
  RUBY
end

#type_cast_code(var_name, type) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/hstore-attributes/hstore_columns.rb', line 40

def type_cast_code(var_name, type)
  klass = ActiveRecord::ConnectionAdapters::Column

  case type.to_sym
  when :string, :text        then var_name
  when :integer              then "(#{var_name}.to_i rescue #{var_name} ? 1 : 0)"
  when :float                then "#{var_name}.to_f"
  when :decimal              then "#{klass}.value_to_decimal(#{var_name})"
  when :datetime, :timestamp then "#{klass}.string_to_time(#{var_name})"
  when :time                 then "#{klass}.string_to_dummy_time(#{var_name})"
  when :date                 then "#{klass}.string_to_date(#{var_name})"
  when :binary               then "#{klass}.binary_to_string(#{var_name})"
  when :boolean              then "#{klass}.value_to_boolean(#{var_name})"
  else var_name
  end
end