Module: ArelAssist

Extended by:
ArelAssist
Included in:
ArelAssist
Defined in:
lib/arel_assist.rb,
lib/arel_assist/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



9
10
11
# File 'lib/arel_assist.rb', line 9

def self.included(base)
  base.extend self
end

Instance Method Details

#arel_count(field) ⇒ Arel::Nodes::NamedFunction

Generates SQL: COUNT(“<table-name>”.“<column-name>”)

Examples:

arel_count(Post.arel_table[:days_active])
#=> 'COUNT("member_summaries"."days_active")'


21
22
23
# File 'lib/arel_assist.rb', line 21

def arel_count(field)
  Arel::Nodes::NamedFunction.new("COUNT", [field])
end

#arel_date_trunc(date_part, field) ⇒ Arel::Nodes::NamedFunction

Generates SQL: date_trunc(‘<date-part>’, “<table-name>”.“<column-name>”)

Examples:

arel_date_trunc('day', MemberSummary.arel_table[:created_at])
#=> "date_trunc('day', \"member_summaries\".\"created_at\")"


34
35
36
# File 'lib/arel_assist.rb', line 34

def arel_date_trunc(date_part, field)
  Arel::Nodes::NamedFunction.new("date_trunc", [sqlv(date_part), field])
end

#arel_max(field) ⇒ Arel::Nodes::NamedFunction

Generates SQL: MAX(“<table-name>”.“<column-name>”)

Examples:

arel_max(Activity.arel_table[:occurred_at])
#=> 'MAX("activities"."occurred_at")'


46
47
48
# File 'lib/arel_assist.rb', line 46

def arel_max(field)
  Arel::Nodes::NamedFunction.new("MAX", [field])
end

#arel_min(field) ⇒ Arel::Nodes::NamedFunction

Generates SQL: MIN(“<table-name>”.“<column-name>”)

Examples:

arel_max(Activity.arel_table[:occurred_at])
#=> 'MIN("activities"."occurred_at")'

with ‘AS’

arel_max(Activity.arel_table[:occurred_at]).as("first_activity_occurred_at")
#=> 'MIN("activities"."occurred_at") AS first_activity_occurred_at'


62
63
64
# File 'lib/arel_assist.rb', line 62

def arel_min(field)
  Arel::Nodes::NamedFunction.new("MIN", [field])
end

#sqlv(node) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/arel_assist.rb', line 66

def sqlv(node)
  case node
  when ->(n) { n.respond_to?(:to_sql) }
    node.to_sql
  when Arel::Attributes::Attribute
    Arel::Nodes::SqlLiteral.new("\"#{node.relation.name}\".\"#{node.name}\"")
  when Array, Range
    value = node.map { |x| x.is_a?(String) ? "'#{x}'" : x }.join(",")
    Arel::Nodes::SqlLiteral.new "ARRAY[#{value}]"
  when Time, DateTime, Date, String
    Arel::Nodes.build_quoted node
  else
    Arel::Nodes::SqlLiteral.new node.to_s
  end
end