class OnCondition

Attributes

current_logic_op[R]
join_table_name[R]
on_table_name[R]
texts[R]

Public Class Methods

new(join_table_name, on_table_name = nil) click to toggle source
# File lib/sql/on_condition.rb, line 5
def initialize join_table_name, on_table_name = nil
  @join_table_name = join_table_name
  @on_table_name   = on_table_name
  @texts = []
  @curent_logic_op = 'and'
  add_default_relation_text
end

Public Instance Methods

add_default_relation_text() click to toggle source
# File lib/sql/on_condition.rb, line 13
def add_default_relation_text
  add_text default_relation_text if default_relation_text
end
add_text(text) click to toggle source
# File lib/sql/on_condition.rb, line 21
def add_text text
  if not texts.include? text
    if texts.size > 0
      texts << [current_logic_op, text].join(" ")
    else
      texts << text 
    end
  end
end
default_relation_text() click to toggle source
# File lib/sql/on_condition.rb, line 36
def default_relation_text
  if on_table_name
    foreign_key = get_foreign_key on_table_name
    "#{join_table_name}.#{foreign_key} = #{on_table_name}.id"
  end
end
text(str) click to toggle source
# File lib/sql/on_condition.rb, line 17
def text str
  add_text str
end
to_statement() click to toggle source
# File lib/sql/on_condition.rb, line 31
def to_statement
  statement = texts.join(" ")
  [join_table_name, "on", statement].join(" ")
end

Private Instance Methods

create_method(name, &block) click to toggle source
# File lib/sql/on_condition.rb, line 82
def create_method name, &block
  self.class.send :define_method, name, &block
end
get_foreign_key(table_name) click to toggle source
# File lib/sql/on_condition.rb, line 53
def get_foreign_key table_name
  "#{table_name.to_s.singularize}_id"
end
method_missing(table_name, values_mapper) click to toggle source
# File lib/sql/on_condition.rb, line 57
def method_missing table_name, values_mapper
  create_method table_name do |values_mapper|
    statement = values_mapper.map {|col, value|
      if value.is_a? Array or value.is_a? Range
        range = value.map {|v| quote v}.join(',')
        "#{table_name}.#{col} in (#{range})"
      else
        "#{table_name}.#{col} = #{quote(value)}"
      end
    }.join(" and ")
    
    text statement
  end
  
 send table_name, values_mapper
end
quote(value) click to toggle source
# File lib/sql/on_condition.rb, line 74
def quote value
  if value.is_a? String
    ["'", value, "'"].join
  else
    value
  end
end
sql_and() click to toggle source
# File lib/sql/on_condition.rb, line 45
def sql_and
  @current_logic_op = 'and'
end
sql_or() click to toggle source
# File lib/sql/on_condition.rb, line 49
def sql_or
  @current_logic_op = 'or'
end