Rails ActiveSuppport:Concern and Private Methods
Asked Answered
L

2

27

This is a great idea about concern in rails: http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns

And it's also a good idea to make very small methods that are not part of a public API. Without using concerns, those become private methods in a ruby class.

Does it makes sense to create private methods inside of a Rails ActiveSupport::Concern module? If so, does private work both for regular instance methods and class methods in the concern definition?

Landlocked answered 18/2, 2013 at 1:21 Comment(0)
D
38

Does it makes sense to create private methods inside of a Rails ActiveSupport::Concern module?

Considering that concerns are smart modules that will eventually be included in other classes — yes, it does. It's just a portable code, extractable behavior and I'd like to consider it as part of my controller (or model, etc.) as I'm writing it. So basically you just declare methods private or protected as you normally would.

Maybe the post you linked have been updated since 2013, but DHH does exactly that in the one of the examples there:

module Dropboxed
  extend ActiveSupport::Concern

  included do
    before_create :generate_dropbox_key
  end

  def rekey_dropbox
    generate_dropbox_key
    save!
  end

  private # <- Let's list some privates

  def generate_dropbox_key
    self.dropbox_key = SignalId::Token.unique(24) do |key| 
      self.class.find_by_dropbox_key(key)
    end
  end
end

As to private class methods, I agree with @Hugo and never used them myself, but here's how you can achieve this:

module Dropboxed
  extend ActiveSupport::Concern

  included do
    private_class_method :method_name
  end

  module ClassMethods
    def method_name
    end
  end
end
Digitiform answered 17/11, 2015 at 22:31 Comment(2)
This will not make the method hidden, you still need to use "private" keyword for this.Apocryphal
It seems that when called from a method of the concern, self.class.method_name is not accessible because private.Incognito
E
4

It's just my opinion but right now I'm scratching my head about private class method, what are they good for? Anyway, if you really need them refer to this post: How to create a private class method?

It does make sense to have private instance methods in a concern module and will work fine. Private class methods will work fine as well but following the above stated post.

Exstipulate answered 18/2, 2013 at 1:47 Comment(1)
it's simple: you need to break you class method into smaller chunks, and don't want to expose those chunks in the class interface. Basically the same reason you would use private methods in any other case.Moreover

© 2022 - 2024 — McMap. All rights reserved.