Answer the question
In order to leave comments, you need to log in
Custom routes to Sinatra (Padrino)?
Greetings!
I am actively mastering the ruby framework - sinatra along with padrino. The task is to organize url generation, which is often used on content sites:
site.ru/category/article-slug.html
in yii, this is solved using its own routing rules www.yiiframework.ru/doc/guide/ru/topics.url
is there a similar opportunity for sinatra?
I understand what can be done by passing two parameters to url_for article and category, but I would like it to pass only the id of the article, and the rule itself makes a selection from the database and forms the url.
Answer the question
In order to leave comments, you need to log in
You just need to write a view helper, something like article_url_for.
In Sinatra, this can be done something like this:
helpers do
def article_url_for(id)
# тут уже напишете выборку объекта из базы или кэша и формирование url
end
end
'/<categoryName:\\w+>/<articleSlug:\\w+>' => "articles/read"
'/<id:\\d+>' => "articles/read"
function actionRead(id = null, categoryName = null, articleSlug = null){
if(!empty(id))
article = Article::model()->findByPk(id)
else
article = Article::model()->findByAttributes(..)
}
$this->createUrl('articles/read', array('categoryName' => 'Books', 'slug' => 'Another-great-book')) //сгенерирует url первого вида
$this->createUrl('articles/read', array('id' => 123)) //сгенерирует url второго вида
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question