Module: Associatable

Included in:
WORMY::Base
Defined in:
lib/wormy/associatable.rb

Instance Method Summary collapse

Instance Method Details

#association_optionsObject



37
38
39
# File 'lib/wormy/associatable.rb', line 37

def association_options
  @association_options ||= {}
end

#belongs_to(name, options = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/wormy/associatable.rb', line 41

def belongs_to(name, options = {})
  options = BelongsToOptions.new(name, options)

  define_method(name) do
    key_value = self.send(options.foreign_key)
    options.model_class.where(options.primary_key => key_value).first
  end

  self.association_options[name] = options
end

#has_many(name, options = {}) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/wormy/associatable.rb', line 52

def has_many(name, options = {})
  options = HasManyOptions.new(name, self, options)

  define_method(name) do
    options.model_class.where(options.foreign_key => self.id)
  end

  self.association_options[name] = options
end

#has_many_through(association_name, through:, source:) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/wormy/associatable.rb', line 88

def has_many_through(association_name, through:, source:)
  define_method(association_name) do
    through_options = self.class.association_options[through]
    source_options = through_options.model_class.association_options[source]

    source_table = source_options.table_name
    through_table = through_options.table_name

    results = WORMY::DBConnection.execute(<<-SQL, self.id)
      SELECT
        #{source_table}.*
      FROM
        #{through_table}
      JOIN
        #{source_table}
      ON
        #{source_table}.#{source_options.foreign_key} = #{through_table}.#{source_options.primary_key}
      WHERE
        #{through_table}.#{through_options.foreign_key} = ?
    SQL

    source_options.model_class.parse_all(results)
  end
end

#has_one_through(association_name, through:, source:) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/wormy/associatable.rb', line 62

def has_one_through(association_name, through:, source:)
  define_method(association_name) do
    through_options = self.class.association_options[through]
    source_options = through_options.model_class.association_options[source]

    source_table = source_options.table_name
    through_table = through_options.table_name
    key_value = self.send(through_options.foreign_key)

    results = WORMY::DBConnection.execute(<<-SQL, key_value)
      SELECT
        #{source_table}.*
      FROM
        #{through_table}
      JOIN
        #{source_table}
      ON
        #{through_table}.#{source_options.foreign_key} = #{source_table}.#{source_options.primary_key}
      WHERE
        #{through_table}.#{through_options.primary_key} = ?
    SQL

    source_options.model_class.parse_all(results).first
  end
end