Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blueprinter: Render Performance Optimisations #289

Closed
wants to merge 10 commits into from
22 changes: 9 additions & 13 deletions lib/blueprinter/formatters/date_time_formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,22 @@ class DateTimeFormatter
def format(value, options)
return value if value.nil?

field_format = options[:datetime_format]
if value.respond_to?(:strftime)
value = format_datetime(value, field_format)
elsif field_format
raise InvalidDateTimeFormatterError, 'Cannot format invalid DateTime object'
end
field_format = options[:datetime_format] || Blueprinter.configuration.datetime_format
return value if field_format.nil?

return format_datetime(value, field_format) if value.respond_to?(:strftime)
raise InvalidDateTimeFormatterError, 'Cannot format invalid DateTime object' if options[:datetime_format]
value
end

private

def format_datetime(value, field_format)
format = field_format || Blueprinter.configuration.datetime_format

case format
when NilClass then value
when Proc then format.call(value)
when String then value.strftime(format)
case field_format
when Proc then field_format.call(value)
when String then value.strftime(field_format)
else
raise InvalidDateTimeFormatterError, 'Cannot format DateTime object with invalid formatter: #{format.class}'
raise InvalidDateTimeFormatterError, 'Cannot format DateTime object with invalid formatter: #{field_format.class}'
end
end
end
Expand Down
16 changes: 10 additions & 6 deletions lib/blueprinter/view_collection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ def initialize
default: View.new(:default)
}
@sort_by_definition = Blueprinter.configuration.sort_fields_by.eql?(:definition)
@fields_for = {}
end

def inherit(view_collection)
Expand All @@ -21,12 +22,15 @@ def has_view?(view_name)
end

def fields_for(view_name)
return identifier_fields if view_name == :identifier

fields, excluded_fields = sortable_fields(view_name)
sorted_fields = sort_by_definition ? sort_by_def(view_name, fields) : fields.values.sort_by(&:name)

(identifier_fields + sorted_fields).reject { |field| excluded_fields.include?(field.name) }
@fields_for[view_name] ||=
if view_name == :identifier
identifier_fields
else
fields, excluded_fields = sortable_fields(view_name)
sorted_fields = sort_by_definition ? sort_by_def(view_name, fields) : fields.values.sort_by(&:name)

(identifier_fields + sorted_fields).reject { |field| excluded_fields.include?(field.name) }
end
end

def transformers(view_name)
Expand Down