Module: Alula::RelationshipAttributes

Defined Under Namespace

Modules: InstanceMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



3
4
5
6
7
8
# File 'lib/alula/relationship_attributes.rb', line 3

def self.extended(base)
  base.class_eval do
    @relationships = {}
  end
  base.include(InstanceMethods)
end

Instance Method Details

#check_relationship!(possible_r) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/alula/relationship_attributes.rb', line 56

def check_relationship!(possible_r)
  cleaned_relationship = Util.underscore(possible_r).to_sym

  unless self.relationship_exists?(cleaned_relationship)
    error = "Invalid relationship #{cleaned_relationship} for class #{self}. "\
            "Please use one of #{get_relationships.keys.join(', ')}"
    raise Alula::InvalidRelationshipError.new(error)
  end

  cleaned_relationship
end

#get_relationship(name) ⇒ Object



45
46
47
48
49
50
# File 'lib/alula/relationship_attributes.rb', line 45

def get_relationship(name)
  identifier = name.is_a?(Symbol) ? :name : :type
  relationship = get_relationships.find { |_key, opts| opts[identifier] == name }
  raise "Unknown relationship #{identifier} #{name} for class #{self}" unless relationship
  relationship.last
end

#get_relationshipsObject



41
42
43
# File 'lib/alula/relationship_attributes.rb', line 41

def get_relationships
  @relationships
end

#relationship(name, **opts) ⇒ Object

TODO: Walk the relationships and define methods to allow an instance to

request a relationship with dot notation... Dealer.fetch(id).devices, etc


12
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
# File 'lib/alula/relationship_attributes.rb', line 12

def relationship(name, **opts)
  @relationships ||= {}
  @relationships[name] = opts.merge(name: name)
  
  # Define a getter for our relationship name
  instance_eval do
    define_method(name) do
      @related_models[name]
    end
  end

  if opts[:cardinality] == 'To-one'
    instance_eval do
      define_method("#{name}=") do |new_model|
        @related_models[name] = new_model
      end
    end
  elsif opts[:cardinality] == 'To-many'
    instance_eval do
      define_method("#{name}<<") do |new_model|
        @related_models[name] ||= ListObject.new(self.class)
        @related_models[name] << new_model
      end
    end
  end

  @relationships
end

#relationship_exists?(possible_r) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/alula/relationship_attributes.rb', line 52

def relationship_exists?(possible_r)
  get_relationships.keys.include?(possible_r.to_sym)
end