Class: Attrio::AttributesParser

Inherits:
Object
  • Object
show all
Defined in:
lib/attrio/attributes_parser.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, options, &block) ⇒ AttributesParser

Returns a new instance of AttributesParser.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
# File 'lib/attrio/attributes_parser.rb', line 7

def initialize(object, options, &block)
  @object = object
  @options = options

  raise ArgumentError.new('Missing options[:as] value' ) if @options[:as].blank?

  self.instance_eval(&block)
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



5
6
7
# File 'lib/attrio/attributes_parser.rb', line 5

def klass
  @klass
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/attrio/attributes_parser.rb', line 5

def options
  @options
end

Class Method Details

.cast_type(constant) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/attrio/attributes_parser.rb', line 27

def self.cast_type(constant)
  return constant if constant.is_a?(Class) && !!(constant < Attrio::Types::Base)

  string = constant.to_s
  string = string.camelize if (string =~ /\w_\w/ || string.chars.first.downcase == string.chars.first)
  
  begin
    if Attrio::Types.const_defined?(string)
      return Attrio::Types.const_get(string)
    elsif Object.const_defined?(string)
      return Object.const_get(string)
    else
      return nil
    end
  rescue
    return constant
  end
end

Instance Method Details

#attr(*args) ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/attrio/attributes_parser.rb', line 16

def attr(*args)
  attribute_options = args.extract_options!
  attribute_name = args[0].to_s

  type = self.class.cast_type(attribute_options.delete(:type) || args[1])      
  self.class.const_missing(attribute_options.delete(:type).to_s || args[1].to_s) if type.blank?

  attribute = Attrio::Attribute.new(@object, attribute_name, type, attribute_options).define_writer.define_reader
  self.add_attribute(attribute_name, attribute)
end