0

Is there a way to have a model such that only code within the same module can access it?

Something like:

module SomeModule
  class SomeActiveRecordModel
    # has attribute `some_attribute`
    ...
  end
end

module SomeModule
  class SomeOtherClass
    def self.sum_of_attribute
      SomeActiveRecordModel.sum(:some_attribute)
    end
  end
end

class OutsideOfModule
  def self.sum_of_attribute
    SomeModule::SomeActiveRecordModel.sum(:some_attribute)
  end
end

SomeModule::SomeOtherClass.sum_of_attribute # works
OutsideOfModule.sum_of_attribute # raises error
bmasc
  • 2,410
  • 2
  • 15
  • 9
  • shouldn't this raise error already? From `OutsideOfModule`, you need to do `SomeModule:: SomeActiveRecordModel` in order to refer to the class. – Edmund Lee Jan 17 '17 at 22:09
  • True, but not the point of my question. I'll update the method inside `OutsideOfModule` – bmasc Jan 17 '17 at 23:10

2 Answers2

0

Short answer is no. Here's why

Ideally, you want to implement this in your SomeModule. But when you call SomeModule::SomeOtherClass.sum_of_attribute in other classes, you are in a scope of SomeModule::SomeOtherClass.

SomeModule::SomeActiveRecordModel.sum(:some_attribute)
                      ||
                      \/
module SomeModule
  class SomeActiveRecordModel
    def sum(*args)
      # Here, self => SomeModule::SomeActiveRecordModel
      # That's why you won't be able to do any meta trick to the module
      # or classes in the module to identify if it's being invoked outside
    end
  end
end

So you wouldn't know who the original caller is.

You might be able to dig through the call stack to do that. Here's another SO thread you might find helpful if you want to go down that path.

Community
  • 1
  • 1
Edmund Lee
  • 2,514
  • 20
  • 29
0

In short, no. But this is more a question of Ruby's approach and philosophy. There are other ways of thinking about the code that allow you achieve something similar to what you're looking for, in a more Rubyesque way.

This answer covers the different ways of making things private.

Glyoko
  • 2,071
  • 1
  • 14
  • 28