Skip to content

Howto : create a builder and formatter

giniedp edited this page Jul 4, 2012 · 6 revisions

Sometimes the fancygrid setup might get very large and you wish to have it in some other place, to not clutter your controller action. For this you can pass a builder class to the options on setup.

    fancygrid_for :users, :builder => UsersGridBuilder do |grid|
      grid.find
    end

Then define the builder anywhere you like. In that builder you can perform the setup and further define formatter methods for the columns.

    class UsersGridBuilder < Fancygrid::Grid
      # this method will be called on initialization
      # all default options and the ones you passed are in the options parameter
      def apply_options(options)
        # call super to perform basic initialization
        # you could skip this and do your own
        super
        
        # perform all setup as you would do in the fancygrid setup block
        self.attributes :id, :email, username
        self.columns_for :contact do |c|
          c.attributes :street, :zipcode, :city
        end
      end

      # this will format the column that has the users.id identifier
      def format_user_id value
        "ID-#{value}"
      end

      # this will format the column that has the contacts.zipcode identifier
      def format_contacts_zipcode value
        value.to_s.split().join("-")
      end
    end

To define column formatter you have to know the columns identifier. An identifier is generated from the table name of the resource in target and the column name.