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(klass, as, &block) ⇒ AttributesParser

Returns a new instance of AttributesParser.



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

def initialize(klass, as, &block)
  @klass = klass
  @as = as

  self.instance_eval(&block)
end

Instance Attribute Details

#asObject (readonly)

Returns the value of attribute as.



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

def as
  @as
end

#klassObject (readonly)

Returns the value of attribute klass.



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

def klass
  @klass
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 Also known as: attribute



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

def attr(*args)
  attribute_name = args[0].to_s
  attribute_options = (args.last.kind_of?(Hash) ? args.pop : Hash.new)
  attribute_type = self.fetch_type(attribute_options.delete(:type) || args[1])

  attribute = self.create_attribute(attribute_name, attribute_type, attribute_options)
  self.add_attribute(attribute_name, attribute)

  self
end