Rails:分配一个常量,可以在所有控制器中使用

Rails: Assign a constant which can be used in all controllers

class需要在各种控制器动作中使用EWKB,因此定义:

def EWKB
  EWKB = RGeo::WKRep::WKBGenerator.new(:type_format => :ewkb, :emit_ewkb_srid => true, :hex_format => true)
end

def self.containing_latlon(lat, lon, polygon)
  ewkb = EWKB.generate(FACTORY.point(lon, lat).projection)
  where("ST_Intersects(polygon, ST_GeomFromEWKB(E'\\x#{ewkb}'))")
end

以上定义,returnssyntax error: dynamic constant assignment。 相反,我定义了

def EWKB
  RGeo::WKRep::WKBGenerator.new(:type_format => :ewkb, :emit_ewkb_srid => true, :hex_format => true)
end

错误消失了。由于第二个方法需要调用它,我不确定 how/if ruby 会像

那样处理这个构造函数
def self.containing_latlon(lat, lon, polygon)
  EWKB = RGeo::WKRep::WKBGenerator.new(:type_format => :ewkb, :emit_ewkb_srid => true, :hex_format => true)
  ewkb = EWKB.generate(FACTORY.point(lon, lat).projection)
  where("ST_Intersects(polygon, ST_GeomFromEWKB(E'\\x#{ewkb}'))")
end

通往同一个地方

遵循命名约定。常量是 CamelCase,方法和变量名称是 snake_case。口译员正在疯狂地试图理解你想要什么。只需在 application_controller.rb:

中定义一个常量
EWKB = RGeo::WKRep::WKBGenerator.new(:type_format => :ewkb, :emit_ewkb_srid => true, :hex_format => true)

然后使用它。

另一种方法是定义一个方法:

class ApplicationController < ActionController::Base
  def self.ewkb
    # caching the assignment
    @ewkb ||= RGeo::WKRep::WKBGenerator.new(:type_format => :ewkb, :emit_ewkb_srid => true, :hex_format => true)
  end
end

class MyController < ApplicationController
   def my_action
     ApplicationController.ewkb
   end
end

用你喜欢的,不要混用。