Class: Husky::Entity

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

Class Attribute Summary collapse

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



70
71
72
73
# File 'lib/husky/entity.rb', line 70

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

Class Attribute Details

.requiredObject



26
27
28
# File 'lib/husky/entity.rb', line 26

def required
  @required ||= []
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



32
33
34
# File 'lib/husky/entity.rb', line 32

def data
  @data
end

Class Method Details

.attr_required(*args) ⇒ Object



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

def attr_required(*args)
  args.each do |arg|
    self.class_eval("def #{arg};@#{arg};end") unless respond_to? arg
    required << arg
  end
end

.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



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/husky/entity.rb', line 34

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

      (class << self; self; end).class_eval do
        attr_reader key.to_sym
      end
    end
  else
    @data = data
  end
end

#set_basic_attributes_from_hash(hash) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/husky/entity.rb', line 50

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

#valid?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/husky/entity.rb', line 66

def valid?
  self.class.required.all? { |attr| !self.send(attr).nil? }
end