Posts Tagged ‘index’

Ruby on Rails como usar outro layout para uma action

Postado em 12 mar 2009
Categoria(s) Ruby on Rails

Para usar outro layout em uma action específica em Ruby on Rails, é possível fazer o seguinte:

1
2
3
def index
  render :layout => "admin_login"
end

Onde “admin_login” é o layout que você deseja usar.

Se você gostou desse texto e acha que ajudou você, me recomende: Recommend Me.

  • Share/Bookmark

Ruby on Rails 2.2 Como Criar Rss Feed

Postado em 07 fev 2009
Categoria(s) Ruby on Rails

Hoje vou mostrar como criar Rss Feed no Ruby on Rails 2.2, no final você vai dar risada, de tão simples que é. Vamos lá!

Geralmente a action index é responsável por fazer a listagem das informações, ela pode ser parecer com isso:

1
2
3
def index
  @histories = History.find :all, :limit => 10
end

ou como abaixo, quando você está usando o plugin will_paginate:

1
2
3
def index
  @histories = History.paginate :all, :page => params[:page]
end

Não vamos precisar mexer em nada na action index.

Você precisa criar um novo template chamado index.rss.builder, que deve estar localizado em app/views/histories/index.rss.builder com o seguinte conteúdo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
xml.instruct! 'xml', :version => "1.0"
xml.rss :version => "2.0" do
  xml.channel do
    xml.title "Notícias"
    xml.description "Últimas Notícias"
    xml.language('pt-BR')
    xml.link formatted_histories_url(:rss)
 
    for history in @histories
      xml.item do
        xml.title history.title
        xml.description history.content
        xml.pubDate history.created_at.to_s(:rfc822)
        xml.link history_url(history)
        xml.guid history_url(history)
      end
    end
  end
end

Pronto! O que você não acredita que está pronto? É verdade falta adicionar o link no template index.html.erb para ver o Rss Feed.

No template index.html.erb adicione:

1
<%= link_to " RSS Feed", formatted_histories_url(:rss) %>

Para acessar o Rss Feed visite: http://localhost:3000/histories.rss.

Não esqueça de definir no seu arquivo config/routes.rb que o model history trabalha com urls RESTful:

1
map.resources :histories

Uhmm! Não estou feliz ainda, acho que dá para melhorar mais, é verdade podemos adicionar:

1
	<link href="http://localhost:3000/histories.rss" rel="alternate" title="RSS" type="application/rss+xml" />

Entre as tags:

1
<head>...</head>

do HTML, fazendo isso o navegador adiciona o ícone de Feed na barra de endereço e deixa a coisa mais intuitiva para o usuário.

Vamos fazer isso de uma forma mais elegante e dinâmica.

No layout da sua aplicação adicionei yield :auto_discovery entre as tags head do HTML:

1
2
3
4
5
<head>
...
  <%= yield :auto_discovery %>
...
</head>

Agora no template index.html.erb adicione:

1
2
3
<% content_for :auto_discovery do %>
  <%= auto_discovery_link_tag(:rss, :action => :index, :format => :rss) %>
<% end %>

Agora sim ficou legal! ;-)

Mais informações assista aqui: http://media.railscasts.com/videos/087_generating_rss.mov.

Se você gostou desse texto e acha que ajudou você, me recomende: Recommend Me.

  • Share/Bookmark

Ruby on Rails routes RESTful usando only

Postado em 02 fev 2009
Categoria(s) Ruby on Rails

Quando você usa no arquivo routes.rb:

1
map.resources :photos

O Rails cria 7 actions padrões (index, show, new, create, edit, update, e destroy).

Você pode querer apenas usar as actions index e show, desta forma é possível fazer a seguinte configuração:

1
map.resources :photos, : only => [:index, :show]

Se você gostou desse texto e acha que ajudou você, me recomende: Recommend Me.

  • Share/Bookmark

Ext JS criando um combo box através de um JSON JavaScript e adicionando o evento onchange (select)

Postado em 15 jan 2009
Categoria(s) Ext JS, JavaScript

Adicionei na página a biblioteca JavaScript: ext-all.js

Crie no HTML o elemento:

1
2
<div>
  <input type="text" id="local-states" size="20" /></div>

Adicione na página o JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<script language="JavaScript">
// Executado quando a página termina de carregar
Ext.onReady(function() {
 
  // JSON de states para popular o combo box
  var states = [
      {'abbr': 'AL', 'state': 'Alabama', 'nick': 'The Heart of Dixie'},
      {'abbr': 'AK', 'state': 'Alaska', 'nick': 'The Land of the Midnight Sun'},
      {'abbr': 'AZ', 'state': 'Arizona', 'nick': 'The Grand Canyon State'},
      {'abbr': 'AR', 'state': 'Arkansas', 'nick': 'The Natural State'},
      {'abbr': 'CA', 'state': 'California', 'nick': 'The Golden State'},
      {'abbr': 'CO', 'state': 'Colorado', 'nick': 'The Mountain State'},
      {'abbr': 'CT', 'state': 'Connecticut', 'nick': 'The Constitution State'},
      {'abbr': 'DE', 'state': 'Delaware', 'nick': 'The First State'},
      {'abbr': 'DC', 'state': 'District of Columbia', 'nick': "The Nation's Capital"},
      {'abbr': 'FL', 'state': 'Florida', 'nick': 'The Sunshine State'},
      {'abbr': 'GA', 'state': 'Georgia', 'nick': 'The Peach State'},
      {'abbr': 'HI', 'state': 'Hawaii', 'nick': 'The Aloha State'},
      {'abbr': 'ID', 'state': 'Idaho', 'nick': 'Famous Potatoes'},
      {'abbr': 'IL', 'state': 'Illinois', 'nick': 'The Prairie State'},
      {'abbr': 'IN', 'state': 'Indiana', 'nick': 'The Hospitality State'},
      {'abbr': 'IA', 'state': 'Iowa', 'nick': 'The Corn State'},
      {'abbr': 'KS', 'state': 'Kansas', 'nick': 'The Sunflower State'},
      {'abbr': 'KY', 'state': 'Kentucky', 'nick': 'The Bluegrass State'},
      {'abbr': 'LA', 'state': 'Louisiana', 'nick': 'The Bayou State'},
      {'abbr': 'ME', 'state': 'Maine', 'nick': 'The Pine Tree State'},
      {'abbr': 'MD', 'state': 'Maryland', 'nick': 'Chesapeake State'},
      {'abbr': 'MA', 'state': 'Massachusetts', 'nick': 'The Spirit of America'},
      {'abbr': 'MI', 'state': 'Michigan', 'nick': 'Great Lakes State'},
      {'abbr': 'MN', 'state': 'Minnesota', 'nick': 'North Star State'},
      {'abbr': 'MS', 'state': 'Mississippi', 'nick': 'Magnolia State'},
      {'abbr': 'MO', 'state': 'Missouri', 'nick': 'Show Me State'},
      {'abbr': 'MT', 'state': 'Montana', 'nick': 'Big Sky Country'},
      {'abbr': 'NE', 'state': 'Nebraska', 'nick': 'Beef State'},
      {'abbr': 'NV', 'state': 'Nevada', 'nick': 'Silver State'},
      {'abbr': 'NH', 'state': 'New Hampshire', 'nick': 'Granite State'},
      {'abbr': 'NJ', 'state': 'New Jersey', 'nick': 'Garden State'},
      {'abbr': 'NM', 'state': 'New Mexico', 'nick': 'Land of Enchantment'},
      {'abbr': 'NY', 'state': 'New York', 'nick': 'Empire State'},
      {'abbr': 'NC', 'state': 'North Carolina', 'nick': 'First in Freedom'},
      {'abbr': 'ND', 'state': 'North Dakota', 'nick': 'Peace Garden State'},
      {'abbr': 'OH', 'state': 'Ohio', 'nick': 'The Heart of it All'},
      {'abbr': 'OK', 'state': 'Oklahoma', 'nick': 'Oklahoma is OK'},
      {'abbr': 'OR', 'state': 'Oregon', 'nick': 'Pacific Wonderland'},
      {'abbr': 'PA', 'state': 'Pennsylvania', 'nick': 'Keystone State'},
      {'abbr': 'RI', 'state': 'Rhode Island', 'nick': 'Ocean State'},
      {'abbr': 'SC', 'state': 'South Carolina', 'nick': 'Nothing Could be Finer'},
      {'abbr': 'SD', 'state': 'South Dakota', 'nick': 'Great Faces, Great Places'},
      {'abbr': 'TN', 'state': 'Tennessee', 'nick': 'Volunteer State'},
      {'abbr': 'TX', 'state': 'Texas', 'nick': 'Lone Star State'},
      {'abbr': 'UT', 'state': 'Utah', 'nick': 'Salt Lake State'},
      {'abbr': 'VT', 'state': 'Vermont', 'nick': 'Green Mountain State'},
      {'abbr': 'VA', 'state': 'Virginia', 'nick': 'Mother of States'},
      {'abbr': 'WA', 'state': 'Washington', 'nick': 'Green Tree State'},
      {'abbr': 'WV', 'state': 'West Virginia', 'nick': 'Mountain State'},
      {'abbr': 'WI', 'state': 'Wisconsin', 'nick': "America's Dairyland"},
      {'abbr': 'WY', 'state': 'Wyoming', 'nick': 'Like No Place on Earth'}
    ];
 
    // Define o nome para cada posição do JSON de states, armazena todas as informações
    var store = new Ext.data.JsonStore({
      fields: [
        {name: 'abbr', type: 'string'}, // nome de cada coluna do JSON de states
        {name: 'state', type: 'string'},
        {name: 'nick', type: 'string'}
      ],
      data: states // JSON de states
    });
 
    // Cria o combo box
    var combo = new Ext.form.ComboBox({
      store: store, // Define o armazenamento das informações
      displayField: 'state', // Coluna que será exibida no combo box
      typeAhead: true, // Leia a api: http://extjs.com/deploy/ext/docs/output/Ext.form.ComboBox.html
      mode: 'local', // Leia a api: http://extjs.com/deploy/ext/docs/output/Ext.form.ComboBox.html
      forceSelection: true, // Leia a api: http://extjs.com/deploy/ext/docs/output/Ext.form.ComboBox.html
      triggerAction: 'all', // Leia a api: http://extjs.com/deploy/ext/docs/output/Ext.form.ComboBox.html
      emptyText: 'Select a state...', // Texto no combo box quando nenhum elemento está selecionado
      selectOnFocus: true, // Leia a api: http://extjs.com/deploy/ext/docs/output/Ext.form.ComboBox.html
      applyTo: 'local-states' // Campo input que será usado para gerar o combo box
    });
 
    // Evento disparado quando é selecionado um item no combo box
    combo.addListener('select', handleSelect);
});
 
function handleSelect(obj, record, index) {
  // Imprime todas as informações da opção selecionada no combo box
  alert('Selecionou a opção: abbr: ' + record.get('abbr') + ', state: ' + record.get('state') + ', nick: ' + record.get('nick') + ', index: ' + index);
}
</script>

Leia os comentários no código para entender como toda essa macumba funciona! ;-)

  • Share/Bookmark