Aaron Vegh
Aaron Vegh

Reputation: 5217

Rails model "before_filter"?

I know that before_filter is only for controllers in Rails, but I would like something like this for a model: any time a method in my model is called, I'd like to run a method that determines whether the called method should run. Conceptually, something like this:

class Website < ActiveRecord::Base
  before_filter :confirm_company

  def confirm_company
    if self.parent.thing == false?
      return false
    end
  end

  def method1
    #do stuff
  end

end

So when I call @website.method1, it will first call confirm_company, and if I return false, will not run method1. Does Rails have functionality like this? I hope i'm just missing out on something obvious here...

Upvotes: 12

Views: 12565

Answers (2)

Edmund Lee
Edmund Lee

Reputation: 2572

I've made a gem just for this.

You can plug this in any ruby class, and do something like in the controller.

before_action :foobar, on: [:foo]

https://github.com/EdmundLeex/action_callback

Upvotes: 2

Robin
Robin

Reputation: 21884

class MyModel
    extend ActiveModel::Callbacks
    define_model_callbacks :do_stuff

    before_do_stuff :confirm

    def do_stuff
        run_callbacks :do_stuff do
            #your code
        end
    end

    def confirm
        #confirm
    end
end

I'm really not sure this will work, but you can try it, as I really dont have time now. Take a look at that: http://api.rubyonrails.org/classes/ActiveModel/Callbacks.html

Upvotes: 12

Related Questions