inesita-rb / inesita

Frontend web application framework in Ruby using Opal.
https://inesita.fazibear.me/
MIT License
259 stars 15 forks source link

href with dynamic url param #9

Closed olegantonyan closed 8 years ago

olegantonyan commented 8 years ago

Hi I'm playing with Inesita and have a trouble. I want to create a link to a component which accepts an id parameter (or whatever another parameter). Like this:

def routes
  route '/devices', to: Devices::Index do
    route '/:id', to: Devices::Show
  end
end

Device::Show component

module Devices
  class Show
    include Inesita::Component

    def render
      component Devices::Device, props: props # how to extract :id url param? router.path.split('/').last is kind of ugly
    end
  end
end

Where Devices::Device is like a rails partial

module Devices
  class Device
    include Inesita::Component

    def render
      div class: 'jumbotron text-center' do
        p do
          text props
        end
      end
    end
  end
end

And Device::Index looks like this

module Devices
  class Index
    include Inesita::Component

    def render
      [1,2,3,4,5].each do |i|
        div do
          a href: router.url_for(Devices::Show).gsub(':id', i.to_s) do # how to pass `i` as id prop?
            text i
          end
        end
      end
    end
  end
end

How can extract url parameter in a component? Or there is another approach instead of REST-like for frontend app made of components?

Thanks

fazibear commented 8 years ago

Hi!

There is a router method available in every component. And router.params is a hash that contains your id.

Here is example:

in Device::Show component

module Devices
  class Show
    include Inesita::Component

    def render
      component Devices::Device, props: router.params[:id] # router.params is hash
    end
  end
end
olegantonyan commented 8 years ago

Thanks! This is exactly what I need

btw, I think it would be nice if we could pass params to url_for, more like link_to in rails. So, ugly router.url_for(Devices::Show).gsub(':id', 100500) will become router.url_for(Devices::Show, id: 100500). Or I also missed this?

fazibear commented 8 years ago

You're right, router.url_for should take an optional params. I need to fix this. Thanks. Also current_url? will not work if there is an param within.

fazibear commented 8 years ago

Fixed in master.

fazibear commented 8 years ago

0.3.1 released, you can update and use url_for with options hash :+1:

olegantonyan commented 8 years ago

Very cool! Thank!