Class: Rseed::Attribute

Inherits:
Object
  • Object
show all
Includes:
AttributeConverters
Defined in:
lib/rseed/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from AttributeConverters

#deserialize_boolean, #deserialize_clean_string, #deserialize_date, #deserialize_datetime, #deserialize_decimal, #deserialize_string

Constructor Details

#initialize(name, options = {}) ⇒ Attribute

Returns a new instance of Attribute.



8
9
10
11
# File 'lib/rseed/attribute.rb', line 8

def initialize(name, options = {})
  @name = name
  @options = options
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



5
6
7
# File 'lib/rseed/attribute.rb', line 5

def name
  @name
end

#optionsObject

Returns the value of attribute options.



6
7
8
# File 'lib/rseed/attribute.rb', line 6

def options
  @options
end

Instance Method Details

#deserialize(values, deserialize_options = {}) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rseed/attribute.rb', line 24

def deserialize values, deserialize_options = {}
  return nil if values[self.name].nil?
  value = values[self.name]

  if options[:model_attribute] || options[:model]
    model = options[:model] || true
    model_attribute = options[:model_attribute] || :id
    # The attribute is a model, we look up the model via the specified attribute
    model_name = model == true ? self.name : model
    klass = model_name.is_a?(Class) ? model_name : model_name.to_s.classify.constantize
    model_match = options[:model_match] || :first
    value = klass.where(model_attribute => value).send(model_match.to_s)
  elsif options[:type]
    # Check for a deserialize function for the type
    dsf = "deserialize_#{options[:type].to_s}"
    if deserialize_options[:converter] && deserialize_options[:converter].respond_to?(dsf)
      value = deserialize_options[:converter].send(dsf, value)
    elsif self.respond_to? dsf
      value = self.send(dsf, value)
    end
  end
  value
end

#headerObject



13
14
15
# File 'lib/rseed/attribute.rb', line 13

def header
  return options[:header] || name
end

#matches?(match_name) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
# File 'lib/rseed/attribute.rb', line 17

def matches? match_name
  #return true if options[:header] and match_name == options[:header]
  match = options[:match] || /^#{Regexp.escape(self.name)}$/i
  re = match.is_a?(Regexp) ? match : Regexp.new(match, true)
  !re.match(match_name).nil?
end