Module: DB2Query::Core::ClassMethods

Defined in:
lib/db2_query/core.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object (private)



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/db2_query/core.rb', line 68

def method_missing(method_name, *args, &block)
  sql_methods = self.instance_methods.grep(/_sql/)
  sql_method = "#{method_name}_sql".to_sym

  if sql_methods.include?(sql_method)
    sql_statement = allocate.method(sql_method).call

    unless sql_statement.is_a? String
      raise ArgumentError, "Query methods must return a SQL statement string!"
    end

    query(method_name, sql_statement)

    method(method_name).call(*args)
  else
    super
  end
end

Instance Method Details

#attributes(attr_name, format) ⇒ Object



39
40
41
# File 'lib/db2_query/core.rb', line 39

def attributes(attr_name, format)
  formatters.store(attr_name, format)
end

#query(name, sql_statement) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/db2_query/core.rb', line 43

def query(name, sql_statement)
  if defined_method_name?(name)
    raise ArgumentError, "You tried to define a scope named \"#{name}\" " \
      "on the model \"#{self.name}\", but DB2Query already defined " \
      "a class method with the same name."
  end

  unless sql_statement.strip.match?(/^select/i)
    raise NotImplementedError
  end

  self.class.define_method(name) do |*args|
    connection.exec_query(sql_statement, formatters, args)
  end
end