Class: Magellan::Subscriber::Mapper

Inherits:
Object
  • Object
show all
Defined in:
lib/magellan/subscriber/mapper.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(map_file_path = self.class.default_mapper_file) ⇒ Mapper

Returns a new instance of Mapper.



17
18
19
20
21
22
23
24
25
# File 'lib/magellan/subscriber/mapper.rb', line 17

def initialize(map_file_path=self.class.default_mapper_file)
  # テストのため nil で初期化できるようにしています
  if map_file_path
    @config_file = map_file_path.to_s
    @config_file_size = nil
    @config_file_mtime = nil
    load_mapper_file
  end
end

Class Method Details

.default_mapper_fileObject



9
10
11
12
13
14
15
# File 'lib/magellan/subscriber/mapper.rb', line 9

def self.default_mapper_file
  map_file_path = ::Rails.root.join("config/subscriptions.yml")
  unless map_file_path.readable?
    map_file_path = ::Rails.root.join("config/subscribes.yml")
  end
  map_file_path.to_path
end

Instance Method Details

#call(request) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
# File 'lib/magellan/subscriber/mapper.rb', line 103

def call(request)
  actions = map_action(request.topic)
  actions.each do |controller_name, action|
    controller_class = ActiveSupport::Dependencies.constantize(controller_name)
    controller = controller_class.new(request)
    controller.process_action(action)
  end
  if actions.empty?
    raise Magellan::Subscriber::RoutingError, "topic #{request.topic} has no matched subscriber"
  end
end

#load_mapper_fileObject



27
28
29
30
31
32
33
34
35
# File 'lib/magellan/subscriber/mapper.rb', line 27

def load_mapper_file
  if @config_file
    st = File.stat(@config_file)
    if st.size != @config_file_size or st.mtime > @config_file_mtime
      @config = YAML.load(File.read(@config_file))
      self.map = @config
    end
  end
end

#mapObject



88
89
90
91
92
93
# File 'lib/magellan/subscriber/mapper.rb', line 88

def map
  if Rails.env.development?
    load_mapper_file
  end
  @map
end

#map=(config) ⇒ Object



79
80
81
82
83
84
85
86
# File 'lib/magellan/subscriber/mapper.rb', line 79

def map=(config)
  @map = config.each_with_object({}) do |(key, value), tbl|
    regexp = topic_regexp(key)
    controller, action = value.split("#", 2)
    controller_name = (controller.camelize + "Subscriber")
    tbl[regexp] = [controller_name, action]
  end
end

#map_action(topic) ⇒ Object



95
96
97
98
99
100
101
# File 'lib/magellan/subscriber/mapper.rb', line 95

def map_action(topic)
  self.map.select do |re, _|
    re.match(topic)
  end.map do |_, (controller_name, action)|
    [controller_name, action]
  end
end