Module: HstoreAttributes

Defined in:
lib/hstore_attributes.rb,
lib/hstore_attributes/version.rb

Constant Summary collapse

VERSION =
"1.0.3"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.convert(value, options = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/hstore_attributes.rb', line 4

def self.convert(value, options = {})
  if options[:allow_nil] and value.nil?
    nil
  elsif options[:type_cast]
    options[:type_cast].to_proc.call(value)
  else
    value
  end
end

Instance Method Details

#hstore_accessor(hstore, *attributes) ⇒ Object



34
35
36
37
# File 'lib/hstore_attributes.rb', line 34

def hstore_accessor(hstore, *attributes)
  hstore_reader(hstore, *attributes)
  hstore_writer(hstore, *attributes)
end

#hstore_reader(hstore, *attributes) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/hstore_attributes.rb', line 14

def hstore_reader(hstore, *attributes)
  options = attributes.extract_options!
  attributes.map(&:to_s).each do |attribute|
    define_method(attribute) do
      value = (send(hstore) || {})[attribute]
      HstoreAttributes.convert(value, options)
    end
  end
end

#hstore_writer(hstore, *attributes) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/hstore_attributes.rb', line 24

def hstore_writer(hstore, *attributes)
  options = attributes.extract_options!
  attributes.map(&:to_s).each do |attribute|
    define_method("#{attribute}=") do |value|
      value = HstoreAttributes.convert(value, options)
      send("#{hstore}=", (send(hstore) || {}).merge(attribute => value))
    end
  end
end