Class: Husky::Entity

Inherits:
Object
  • Object
show all
Defined in:
lib/husky/entity.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



55
56
57
58
# File 'lib/husky/entity.rb', line 55

def method_missing(method, *args, &block)
  raise "#{method} called on @data, but @data is nil." if data.nil?
  data.send(method, *args, &block)
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



19
20
21
# File 'lib/husky/entity.rb', line 19

def data
  @data
end

Class Method Details

.build(data = nil) ⇒ Object



11
12
13
14
15
# File 'lib/husky/entity.rb', line 11

def build(data = nil)
  instance = allocate
  instance.construct(data)
  instance
end

.wrap(items) ⇒ Object



7
8
9
# File 'lib/husky/entity.rb', line 7

def wrap(items)
  items.map { |item| build(item) }
end

Instance Method Details

#construct(data) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/husky/entity.rb', line 21

def construct(data)
  if data.nil?
    # do nothing
  elsif data.is_a? Hash
    data.each_pair do |key, value|
      instance_variable_set("@#{key}", value)
    end

    data.each_pair do |key, value|
      self.class.send(:define_method, key) do
        instance_variable_get("@#{key}")
      end
    end
  else
    @data = data
  end
end

#set_basic_attributes_from_hash(hash) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/husky/entity.rb', line 39

def set_basic_attributes_from_hash(hash)
  hash.each_pair do |key, value|
    unless value.respond_to? :each
      instance_variable_set("@#{key}", value)
    end
  end

  hash.each_pair do |key, value|
    unless value.respond_to? :each
      self.class.send(:define_method, key) do
        instance_variable_get("@#{key}")
      end
    end
  end
end