Jerome
Jerome

Reputation: 6189

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

The class needs to use EWKB in various controller actions, thus defined:

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

The above definition, returns syntax error: dynamic constant assignment. In its stead, I defined

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

and the error disappears. As the second method needs to invoke it, I am not certain how/if ruby will handle this constructor as

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

leads to the same spot

Upvotes: 1

Views: 125

Answers (1)

EugZol
EugZol

Reputation: 6545

Follow naming conventions. Constants are CamelCase, method and variable names are snake_case. Interpreter are going mad trying to understand what do you want. Just define a constant in your application_controller.rb:

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

And then use it.

Another way is to define a method:

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

Use what you like, just don't mix them.

Upvotes: 1

Related Questions