Skip to content

Instantly share code, notes, and snippets.

@astevens
Created December 8, 2014 20:30
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 astevens/b80225d96d8889c946ac to your computer and use it in GitHub Desktop.
Save astevens/b80225d96d8889c946ac to your computer and use it in GitHub Desktop.
format all dates and times as iso iso8601 in RABL output
# config/initializers/rabl.rb
# monkey patch to format date automatically
module Rabl
class Configuration
attr_accessor :force_iso_dates
end
class Builder
def to_hash(object = nil, settings = {}, options = {})
@_object = object if object
@options.merge!(options) if options
@settings.merge!(settings) if settings
cache_results do
@_result = {}
# Merges directly into @_result
compile_settings(:attributes)
merge_engines_into_result
# Merges directly into @_result
compile_settings(:node)
replace_nil_values if Rabl.configuration.replace_nil_values_with_empty_strings
replace_empty_string_values if Rabl.configuration.replace_empty_string_values_with_nil_values
remove_nil_values if Rabl.configuration.exclude_nil_values
force_iso_dates if Rabl.configuration.force_iso_dates
result = @_result
result = { @options[:root_name] => result } if @options[:root_name].present?
result
end
end
protected
def force_iso_dates
@_result = @_result.inject({}) do |new_hash, (k, v)|
new_hash[k] = v.respond_to?(:iso8601) ? v.iso8601 : v
new_hash
end
end
end
end
Rabl.configure do |config|
# These are the default
# config.cache_templates = true
# config.include_json_root = true
# config.json_engine = ::Oj
# config.xml_options = { :dasherize => true, :skip_types => false }
# config.use_custom_responder = false
# config.default_responder_template = 'show'
# config.enable_jsonp_callbacks = false
# config.replace_nil_values_with_empty_strings = false
# config.replace_empty_string_values_with_nil = false
# config.exclude_nil_values = false
config.force_iso_dates = true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment