Skip to content

Instantly share code, notes, and snippets.

@duykhoa
Last active August 29, 2015 14:17
Show Gist options
  • Save duykhoa/e3f6a9afdcaf6842b7c6 to your computer and use it in GitHub Desktop.
Save duykhoa/e3f6a9afdcaf6842b7c6 to your computer and use it in GitHub Desktop.
Kaminari basic

Kaminari (Coding)

###A. Support part

####1. extend, include.

Ex1:

module A
  def self.included(class_name)
    class_name.send(:extend, B)
  end

  module B
    def method1
    end
  end
end

class C
  include A
end

So C.method1 or C.new.method1 raise an error. Explain.

####2. Singleton Class

Ex2:

There is an instance of ServiceOrder model

my_so = ServiceOrder.new
example, inside ServiceOrder model, we have:

class ServiceOrder
  def to_s
    "I am a service order"
  end
end

so my_so.to_s will return "I am a service order"

but if we have

class << my_so
  def to_s
    "Are you sure?"
  end
end

What is the result of my_so.to_s? "Are you sure?" ^^ However, guess what is returned ServiceOrder.new.to_s

  1. Remind Chain method

The example for Select class:

select = Select.new(4)
select.add_option(5).and(2).and(3).and(4)
select.options --> [4, 5, 2, 3, 4]

There is a different way, only apply for Active Record Relationship, call extending Check out this method in this link #@TODO

Example:

class Job < ActiveRecord::Base
  def self.lasted_jobs
    order(created_at: :desc).extending do
      def only(num)
        limit(num)
      end
    end.extending do
      def random
        sample
      end
    end
  end
end

After that, we can write some awesome code with it, for ex:

Job.latest_jobs

Job.latest_jobs.only(5)

Job.latest_jobs.only(5).random

Wow. Check out how it work :)

###B. Works

  1. We often see somethings like this in a concern
included_do
  validates :name, presence: true
  include ModuleB
end

but if we wirte the block code without the ``included_do...end```, it will returns errors. How does it works?

  1. Check the model/active_record_model_extension.rb. The method:
  def inherited(kls) #:nodoc:
    super
    kls.send(:include, Kaminari::ActiveRecordModelExtension) if kls.superclass == ::ActiveRecord::Base
  end

a. This method is a class/instance method? b. As we see, if its superclass is AR::Base, we will include the module Kaminari::ActiceRecordModelExtension, so how does this method is call?

  1. How to change the page method to something else in kaminari configure, ex. bulk, or group
  2. How does link_to_if work?
  3. How to implement kaminari with an array
  4. What is padding concept in kaminari :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment