Ruby Rails:指定一个可在所有控制器中使用的常量
该类需要在各种控制器操作中使用Ruby Rails:指定一个可在所有控制器中使用的常量,ruby,ruby-on-rails-3.2,Ruby,Ruby On Rails 3.2,该类需要在各种控制器操作中使用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).
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
上述定义返回语法错误:动态常数赋值
。
取而代之的是,我定义了
def EWKB
RGeo::WKRep::WKBGenerator.new(:type_format => :ewkb, :emit_ewkb_srid => true, :hex_format => true)
end
错误消失了。由于第二个方法需要调用它,我不确定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\u case
。翻译正在疯狂地试图理解你想要什么。只需在应用程序\u 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
class ApplicationController:ewkb,:emit_ewkb_srid=>true,:hex_format=>true)
结束
结束
类MyController
你喜欢用什么就用什么,只是不要把它们混在一起