Created
March 15, 2012 20:43
-
-
Save hopsoft/2046768 to your computer and use it in GitHub Desktop.
Hashify helper for ActiveRecord models
This file contains 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
module JsonHashifier | |
# Converts an ActiveRecord model object to a JSON appropriate Hash. | |
# @param [Hash] options | |
# @option options [String] :timezone The timezone to apply to the created_at & updated_at columns | |
# @option options [Integer] :timezone_offset The timezone offset that should be used to determine the timezone | |
# @option options [String] :date_format The strftime format to apply to the created_at & updated_at columns | |
# @option options [Boolean] :indifferent_access Indicates whether or not to return a HashWithIndifferentAccess | |
# @options options [Array<String,Symbol>] :whitelist A white list of attributes to keep in the Hash. Defaults to all attributes. | |
# @options options [Array<String,Symbol>] :methods A list of methods to invoke for inclusion in the Hash. | |
# Note that the method must not accept any arguments. | |
def hashify_for_json(options={}) | |
options[:timezone_offset] = options[:timezone_offset].to_i | |
if options[:timezone].blank? | |
timezone_names = ActiveSupport::TimeZone::MAPPING.keys.select do |name| | |
ActiveSupport::TimeZone[name].utc_offset == options[:timezone_offset] | |
end | |
options[:timezone] = timezone_names.first || "UTC" | |
end | |
options[:date_format] ||= "%a, %b %d, %Y %I:%M %p" | |
attrs = attributes | |
attrs = HashWithIndifferentAccess.new(attrs) if options[:indifferent_access] | |
attrs = attrs.merge( | |
:created_at => (created_at.in_time_zone(options[:timezone]).strftime(options[:date_format]) rescue nil), | |
:updated_at => (updated_at.in_time_zone(options[:timezone]).strftime(options[:date_format]) rescue nil) | |
) | |
if options[:whitelist] | |
method = options[:whitelist].first.is_a?(String) ? :to_s : :to_sym | |
attrs.keep_if { |k, v| options[:whitelist].nil? || options[:whitelist].include?(k.send(method)) } | |
end | |
(options[:methods] || []).each {|m| attrs[method] = send(m) } | |
attrs | |
end | |
end | |
# Example useage | |
# app/models/user.rb | |
class User < ActiveRecord::Base | |
include JsonHashifier | |
end | |
# app/controllers/users_controller.rb | |
class UsersController < ApplicationController | |
def index | |
@users = User.all.map do |user| | |
user.hashify_for_json(:indifferent_access => true) | |
.merge(:some_number_for_example => rand(10)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment