Class: Croudia::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/croudia/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Croudia::Base

Initialize a new object

Parameters:

  • attrs (Hash) (defaults to: {})


47
48
49
# File 'lib/croudia/base.rb', line 47

def initialize(attrs = {})
  @attrs = attrs
end

Class Method Details

.attr_object_reader(attrs) ⇒ Object

Parameters:

  • attrs (Hash)

    { name: Class, name: Class, … }



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/croudia/base.rb', line 13

def attr_object_reader(attrs)
  attrs.each_pair do |path, klass|
    path = [path] unless path.is_a?(Array)
    attr = path.join('_').to_sym

    define_method(path.last) do
      object = instance_variable_get("@#{attr}")

      unless object
        object_attrs = @attrs
        path.each { |p| object_attrs = object_attrs[p.to_s] }

        object = if object_attrs.nil?
          nil
        elsif klass.is_a?(Array)
          klass = klass.shift
          object_attrs.map { |o| klass.new(o) }
        else
          klass.new(object_attrs)
        end

        instance_variable_set("@#{attr}", object)
      end

      object
    end
  end
end

.attr_reader(*attrs) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/croudia/base.rb', line 4

def attr_reader(*attrs)
  attrs.each do |attr|
    define_method(attr) do
      @attrs[attr.to_s] || @attrs[attr.to_sym]
    end
  end
end

Instance Method Details

#[](name) ⇒ Object

Fetch an attribute

Parameters:

  • name (String, Symobol)


54
55
56
57
58
# File 'lib/croudia/base.rb', line 54

def [](name)
  __send__(name.to_sym)
rescue NoMethodError
  nil
end

#attrsHash Also known as: to_h, to_hash

Returns:

  • (Hash)


61
62
63
# File 'lib/croudia/base.rb', line 61

def attrs
  @attrs
end

#inspectObject



67
68
69
# File 'lib/croudia/base.rb', line 67

def inspect
  "#<#{self.class} #{@attrs.inspect}>"
end