开发者

Create property as method on class in Ruby

开发者 https://www.devze.com 2023-04-03 20:44 出处:网络
Rails has these cool properties that seem to be actually methods. For example: class SomeController < ApplicationController

Rails has these cool properties that seem to be actually methods. For example:

class SomeController < ApplicationController

  before_filter :authenticate!

end

What are these actually called and how would you create your own? For e开发者_C百科xample, in one of my models I want to be able to have a dynamic property that selects an internal method for processing some results:

class MyModel < ActiveRecord::Base

    active_method :some_class_method

end

How would I set this up so I can set active_method like that and be able to access the active_method symbol as an instance var?

Edit for elaboration:

So give this starter below, I need to figure out how to define "selected_method" so that it defines a accessor or instance variable so "called_selected_method" calls "method_b".

class MyClass

  selected_method :method_b

  def call_selected_method

  end

  private

  def method_a
    puts 'method_a'
  end

  def method_b
    puts 'method_b'
  end

end

c = MyClass.new
c.call_selected_method # should put 'method_b'


It's actually just a method call to a method defined on the class. before_filter is provided by a ruby Module, which is mixed in to ActionController.

Creating your own methods similar to before_filter is as easy as:

  1. Define a class method on your Class
  2. Call that method in any concrete implementations of your class.

Some example code:

class MyClass
  class << self
    def some_function(*args)
      # your code here
    end
  end

  some_function "foo"
end

If you wanted to abstract it further, you can put the class method in to a Module, and then include that module in to your class(es).

UPDATE:

In relation to your asking of how to get a call of some_function to set an instance variable on your class, you can't, as class methods cannot affect specific instances of that class.

I have to wonder, though... you're writing a method that will just act as a proxy to your other method, and would be hard-coded in to the class definition. That offers no benefit to you, and would just make your code redundantly complicated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号