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

时间:2015-08-20 08:05:57

标签: 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).projection)
  where("ST_Intersects(polygon, ST_GeomFromEWKB(E'\\\\x#{ewkb}'))")
end

上面的定义,返回syntax error: dynamic constant assignment。 取而代之的是我定义了

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

导致同一地点

1 个答案:

答案 0 :(得分:1)

遵循命名约定。常量为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

使用您喜欢的内容,不要混用它们。