Class: DataContract::Contract

Inherits:
Object
  • Object
show all
Defined in:
lib/data_contract/contract.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mod, obj) ⇒ Contract

Returns a new instance of Contract.



6
7
8
9
# File 'lib/data_contract/contract.rb', line 6

def initialize(mod, obj)
  @mod = mod
  @obj = obj
end

Instance Attribute Details

#modObject (readonly)

Returns the value of attribute mod.



3
4
5
# File 'lib/data_contract/contract.rb', line 3

def mod
  @mod
end

#objObject (readonly)

Returns the value of attribute obj.



4
5
6
# File 'lib/data_contract/contract.rb', line 4

def obj
  @obj
end

Instance Method Details

#assign(val, receiver, attribute) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/data_contract/contract.rb', line 47

def assign(val, receiver, attribute)
  setter = "#{attribute}="

  unless receiver.respond_to?(setter, true)
    raise ContractError, "The #{attribute} attribute cannot be assigned to #{receiver.class.name}"
  end

  receiver.send setter, val
end

#assignable?(other_obj) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
# File 'lib/data_contract/contract.rb', line 30

def assignable?(other_obj)
  unless shared? other_obj
    unless compatible? other_obj
      return false
    end
  end
  true
end

#compatible?(other_obj) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
# File 'lib/data_contract/contract.rb', line 19

def compatible?(other_obj)
  mod.instance_methods(false).each do |m|
    return false unless other_obj.respond_to?(m, true)
  end
  return true
end

#gettersObject



15
16
17
# File 'lib/data_contract/contract.rb', line 15

def getters
  mod.instance_methods(false).select { |m| m.to_s[-1, 1] != '=' }
end

#scatter(receiver) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/data_contract/contract.rb', line 39

def scatter(receiver)
  getters.each do |attribute|
    val = obj.send attribute
    assign val, receiver, attribute
  end
  receiver
end

#settersObject



11
12
13
# File 'lib/data_contract/contract.rb', line 11

def setters
  mod.instance_methods(false).select { |m| m.to_s[-1, 1] == '=' }
end

#shared?(other_obj) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/data_contract/contract.rb', line 26

def shared?(other_obj)
  other_obj.is_a? mod
end