Fred Benfield
Fred Benfield

Reputation: 5

Create a hash when a class object is initialized

I want to create a hash when I initialize a class object.

def initialize
  @url = Hash.new
  Rails.application.routes.routes.named_routes.values.map do |route|
    @url[:request_method] = route.constraints[:request_method].to_s
    @url[:path] = route.path.spec.to_s
    @url[:controller] = route.defaults[:controller]
    @url[:action] = route.defaults[:action]
  end 
end

Once initialized, I am left with just the last returned value instead of a library of stuff to play with. How can I have a library of objects on creation instead of the last returned value?

Upvotes: 0

Views: 45

Answers (1)

tadman
tadman

Reputation: 211690

If you just want to collect and remap those, this should do it:

def initialize
  @urls = Rails.application.routes.routes.named_routes.values.map do |route|
    {
      request_method: route.constraints[:request_method].to_s,
      path: route.path.spec.to_s,
      controller: route.defaults[:controller],
      action: route.defaults[:action]
    }
  end 
end

You'd then create accessor methods to expose @urls in whatever format you want.

Upvotes: 1

Related Questions