Providing another action without changing the url?

I have this code in a Rails 3 controller:

def index
    now = Time.now.utc.strftime("%m%d")
    redirect_to :action => "show", :id => now
end

def show
    begin
        @date = Time.parse("12#{params[:id]}") 
        dbdate = params[:id]
    rescue ArgumentError
        @date = Time.now.utc
        dbdate = @date.strftime("%m%d")
    end

    @date = @date.strftime("%B %d")
    @events = Event.events_for_date(dbdate)
end

So basically the index is just a specialized version of the show, so I want it to execute show, display show.html.erb, but I don’t want to change the URL, for example redirect_to.

I tried this approach:

def index
    now = Time.now.utc.strftime("%m%d")
    params[:id] = now
    show
    render :action => "show"
end

Now it works, but it just smells bad.

I'm new to Ruby and Rails, so I'm just wondering if there is something fundamentally wrong or if there is a better way to do this?

+3
source share
1 answer

What you do there seems beautiful. Writing this a little differently can slightly improve the smell, but the differences are purely cosmetic.

def index
  now = Time.now.utc.strftime("%m%d")
  params[:id] = now
  render_show
end

def show
  render_show
end

private

def render_show
  begin
    @date = Time.parse("12#{params[:id]}") 
    dbdate = params[:id]
  rescue ArgumentError
    @date = Time.now.utc
    dbdate = @date.strftime("%m%d")
  end
  @date = @date.strftime("%B %d")
  @events = Event.events_for_date(dbdate)
  render :action => 'show'
end
+4
source

Source: https://habr.com/ru/post/1782784/


All Articles