繁体   English   中英

我可以禁止从模块外部访问Rails模型吗?

[英]Can I disallow a Rails model from being access outside of a module?

有没有一种方法可以使模型只有同一个模块中的代码可以访问?

就像是:

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

简短的答案是没有。 这就是为什么

理想情况下,您想在SomeModule实现它。 但是,当您在其他类中调用SomeModule::SomeOtherClass.sum_of_attribute时,您将处于SomeModule::SomeOtherClass的作用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线程 ,如果您想走那条路,可能会有所帮助。

简而言之,没有。 但这更多是关于Ruby的方法和哲学的问题。 还有其他思考代码的方法,这些方法可以使您以更像Ruby的方式实现与所需内容相似的功能。

该答案涵盖了使事物私有化的不同方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM