Created
September 26, 2011 08:56
-
-
Save barttenbrinke/1241887 to your computer and use it in GitHub Desktop.
Generate JSON directly in mysql using RAILS proof of concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)