Module: RelationToStruct::ActiveRecordBaseExtension::ClassMethods
- Defined in:
- lib/relation_to_struct/active_record_base_extension.rb
Instance Method Summary collapse
- #_sanitize_sql_for_relation_to_struct(sql) ⇒ Object
- #pluck_from_sql(sql, binds = []) ⇒ Object
- #structs_from_sql(struct_class, sql, binds = []) ⇒ Object
- #tuple_from_sql(sql, binds = []) ⇒ Object
- #value_from_sql(sql, binds = []) ⇒ Object
Instance Method Details
#_sanitize_sql_for_relation_to_struct(sql) ⇒ Object
5 6 7 |
# File 'lib/relation_to_struct/active_record_base_extension.rb', line 5 def _sanitize_sql_for_relation_to_struct(sql) sanitized_sql = ActiveRecord::VERSION::MAJOR >= 5 ? sanitize_sql(sql) : sanitize_sql(sql, nil) end |
#pluck_from_sql(sql, binds = []) ⇒ Object
32 33 34 35 36 |
# File 'lib/relation_to_struct/active_record_base_extension.rb', line 32 def pluck_from_sql(sql, binds=[]) sanitized_sql = _sanitize_sql_for_relation_to_struct(sql) result = connection.select_all(sanitized_sql, "Pluck SQL Load", binds) result.cast_values() end |
#structs_from_sql(struct_class, sql, binds = []) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/relation_to_struct/active_record_base_extension.rb', line 9 def structs_from_sql(struct_class, sql, binds=[]) sanitized_sql = _sanitize_sql_for_relation_to_struct(sql) result = connection.select_all(sanitized_sql, "Structs SQL Load", binds) if result.columns.size != result.columns.uniq.size raise ArgumentError, 'Expected column names to be unique' end if result.columns != struct_class.members.collect(&:to_s) raise ArgumentError, 'Expected column names (and their order) to match struct attribute names' end if result.columns.size == 1 result.cast_values().map do |tuple| struct_class.new(tuple) end else result.cast_values().map do |tuple| struct_class.new(*tuple) end end end |
#tuple_from_sql(sql, binds = []) ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/relation_to_struct/active_record_base_extension.rb', line 54 def tuple_from_sql(sql, binds=[]) sanitized_sql = _sanitize_sql_for_relation_to_struct(sql) result = connection.select_all(sanitized_sql, "Value SQL Load", binds) values = result.cast_values() case values.size when 0 nil when 1 result.columns.size == 1 ? values : values[0] else raise ArgumentError, 'Expected only a single result to be returned' end end |
#value_from_sql(sql, binds = []) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/relation_to_struct/active_record_base_extension.rb', line 38 def value_from_sql(sql, binds=[]) sanitized_sql = _sanitize_sql_for_relation_to_struct(sql) result = connection.select_all(sanitized_sql, "Value SQL Load", binds) raise ArgumentError, 'Expected exactly one column to be selected' unless result.columns.size == 1 values = result.cast_values() case values.size when 0 nil when 1 values[0] else raise ArgumentError, 'Expected only a single result to be returned' end end |