Skip to content

Instantly share code, notes, and snippets.

@barttenbrinke
Created September 26, 2011 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barttenbrinke/1241887 to your computer and use it in GitHub Desktop.
Save barttenbrinke/1241887 to your computer and use it in GitHub Desktop.
Generate JSON directly in mysql using RAILS proof of concept
class ActiveRecord::Base
# Options
# <tt>:only</tt> Only select a specific set of columns
def self.all_as_json(options = {})
find_columns = self.columns.collect{|x| x.name}
find_columns = find_columns.select{|x| options[:only].include?(x)} if options[:only]
sql_query = 'SELECT '
sql_query += "CONCAT("
concat_items = []
concat_items << '"{"'
find_columns.each_with_index do |find_column, index|
concat_items << '"\"' + find_column + '\""'
concat_items << '":"'
concat_items << '"\""'
concat_items << "`#{find_column}`"
concat_items << '"\""'
concat_items << '","' unless index == find_columns.length-1
end
concat_items << '"}"'
sql_query += concat_items.join(',')
sql_query += ") " # Close concat
sql_query += "AS json "
sql_query += "FROM `#{self.table_name}` "
result_set = self.connection.execute(sql_query)
result_array = []
result_set.each_hash do |hash|
result_array << hash['json']
end
"[" + result_array.join(',') + "]"
end
end
@barttenbrinke
Copy link
Author

Why do you want this? Employee.all.to_json will instantiate a heap of activerecord objects for you, only to discard discard them right after the to_json call. Please note that complex types are NOT supported :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment