Skip to content

tskorupa/record_formatter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

record_formatter

RecordFormatter plucks columns from records given a scope, aliased if needed and returns an activerecord relation

Installation


Include this line in your Gemfile

gem "record_formatter", github: "tskorupa/record_formatter"

Usage


Extend the active-record model,

class Foo < ActiveRecord::Base
  scope :recently_updated, -> { where("updated_at >= ?", 5.days.ago) }

  acts_as_record_formatter scope: :recently_updated do
    columns :id, :created_at
    columns :name, alias: :foo_name
  end
end

And apply the method as such,

irb(main):015:0> Foo.format_records
  Foo Load (0.2ms)  SELECT id AS id, created_at AS created_at, name AS foo_name FROM "foos" WHERE (updated_at >= '2015-10-12 16:59:59.225494')
=> #<ActiveRecord::Relation [#<Foo id: 1, created_at: "2015-10-17 16:55:55">]>
irb(main):016:0> Foo.format_records.collect(&:attributes)
  Foo Load (0.2ms)  SELECT id AS id, created_at AS created_at, name AS foo_name FROM "foos" WHERE (updated_at >= '2015-10-12 17:00:04.548358')
=> [{"id"=>1, "created_at"=>Sat, 17 Oct 2015 16:55:55 UTC +00:00, "foo_name"=>"bar"}]

To set a custom scope to retrieve formatted records by (defaults to #format_records):

class Foo < ActiveRecord::Base
  acts_as_record_formatter custom_method_name: :foobarbaz
end

>> Foo.foobarbaz

TODO

  • Add ability to set virtual columns and hardcoded values

  • Add ability to format column values (i.e for a datetime column, value.strftime(“%Y-%m-%d”)

About

RecordFormatter plucks columns from records given a scope, aliased if needed and returns an activerecord relation

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors