Class: MiniSql::InlineParamEncoder
- Inherits:
-
Object
- Object
- MiniSql::InlineParamEncoder
- Defined in:
- lib/mini_sql/inline_param_encoder.rb
Instance Attribute Summary collapse
-
#conn ⇒ Object
readonly
Returns the value of attribute conn.
Instance Method Summary collapse
- #encode(sql, *params) ⇒ Object
- #encode_array(sql, array) ⇒ Object
- #encode_hash(sql, hash) ⇒ Object
-
#initialize(conn) ⇒ InlineParamEncoder
constructor
A new instance of InlineParamEncoder.
- #quote_val(value) ⇒ Object
- #quoted_date(value) ⇒ Object
Constructor Details
#initialize(conn) ⇒ InlineParamEncoder
Returns a new instance of InlineParamEncoder.
7 8 9 |
# File 'lib/mini_sql/inline_param_encoder.rb', line 7 def initialize(conn) @conn = conn end |
Instance Attribute Details
#conn ⇒ Object (readonly)
Returns the value of attribute conn.
5 6 7 |
# File 'lib/mini_sql/inline_param_encoder.rb', line 5 def conn @conn end |
Instance Method Details
#encode(sql, *params) ⇒ Object
11 12 13 14 15 16 17 18 19 20 |
# File 'lib/mini_sql/inline_param_encoder.rb', line 11 def encode(sql, *params) return sql unless params && params.length > 0 if Hash === (hash = params[0]) raise ArgumentError, "Only one hash param is allowed, multiple were sent" if params.length > 1 encode_hash(sql, hash) else encode_array(sql, params) end end |
#encode_array(sql, array) ⇒ Object
39 40 41 42 43 44 45 |
# File 'lib/mini_sql/inline_param_encoder.rb', line 39 def encode_array(sql, array) i = -1 sql.gsub("?") do |p| i += 1 quote_val(array[i]) end end |
#encode_hash(sql, hash) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/mini_sql/inline_param_encoder.rb', line 22 def encode_hash(sql, hash) sql = sql.dup hash.each do |k, v| sql.gsub!(":#{k}") do # ignore ::int and stuff like that # $` is previous to match if $` && $`[-1] != ":" quote_val(v) else ":#{k}" end end end sql end |
#quote_val(value) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/mini_sql/inline_param_encoder.rb', line 51 def quote_val(value) case value when Array value.map do |v| quote_val(v) end.join(', ') when String "'#{conn.escape_string(value.to_s)}'" when true then "true" when false then "false" when nil then "NULL" when BigDecimal then value.to_s("F") when Numeric then value.to_s when Date, Time then "'#{quoted_date(value)}'" when Symbol then "'#{escape_string(value.to_s)}'" else raise TypeError, "can't quote #{value.class.name}" end end |
#quoted_date(value) ⇒ Object
47 48 49 |
# File 'lib/mini_sql/inline_param_encoder.rb', line 47 def quoted_date(value) value.utc.iso8601 end |