Posts Tagged ‘view’

Ruby on Rails plugin pake_browser_detect

Postado em 31 jul 2009
Categoria(s) Plugins, Ruby on Rails

pake_browser_detect

Detecta o browser do usuário.
Pode ser usado na camada de view e na camada de controller.

Disponibiliza dois métodos:

  • browser_name
  • browser_is?

Método browser_name

Retorna o nome do navegador do usuário.

Método browser_is?

Verifica se o navegador do usuário é determinado navegador.

O método browser_is? aceita os símbolos:

  • :firefox
  • :opera
  • :chrome
  • :safari
  • :ie

Instalação

./script/plugin install git://github.com/patrickespake/pake_browser_detect.git

Exemplo

Na camada de view:

<%= browser_name %>
<%= browser_is? :firefox %>

Na camada de controller:

browser_name
browser_is? :firefox

Documentação

http://lab.patrickespake.com/pake_browser_detect

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

  • Share/Bookmark

Ruby on Rails usando strip_tags nos controllers, models e libs

Postado em 15 jun 2009
Categoria(s) Ruby on Rails

O Ruby on Rails possui o métogo strip_tags para remover tags html. Esse método está apenas disponível na camada de view, uma vez que faz parte ActionView::Helpers::SanitizeHelper.

Eu não concordo com essa implementação do Rails, acho que deveria ser disponível também na camada de controller e model, onde são os lugares que esse método é mais útil.

Para implementar o strip_tags nos controllers, models e libs, nós podemos adicionar esse método na classe String, desta forma estará disponível em qualquer lugar.

Abra o arquivo config/initializers/new_rails_defaults.rb:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Be sure to restart your server when you modify this file.
 
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
 
if defined?(ActiveRecord)
  # Include Active Record class name as root for JSON serialized output.
  ActiveRecord::Base.include_root_in_json = true
 
  # Store the full class name (including module namespace) in STI type column.
  ActiveRecord::Base.store_full_sti_class = true
end
 
# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true
 
# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false

Adicione no final do arquivo as linhas:

1
2
3
4
5
class String
  def strip_tags
    ActionController::Base.helpers.strip_tags(self)
  end
end

As linhas acima criam o método strip_tags na classe String.

Ficando o arquivo completo assim:

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
# Be sure to restart your server when you modify this file.
 
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
 
if defined?(ActiveRecord)
  # Include Active Record class name as root for JSON serialized output.
  ActiveRecord::Base.include_root_in_json = true
 
  # Store the full class name (including module namespace) in STI type column.
  ActiveRecord::Base.store_full_sti_class = true
end
 
# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true
 
# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false
 
class String
  def strip_tags
    ActionController::Base.helpers.strip_tags(self)
  end
end

Agora reinicie o seu servidor web para pegar essas novas configurações na inicialização da aplicação.

Agora quando você precisar do strip_tags pode usar assim, exemplos:

params['title'] = params['title'].strip_tags
 
ou
 
>> '<b>meu texto</b>'.strip_tags
=> "meu texto"

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

  • Share/Bookmark

Usando o Vim para Programar em Ruby on Rails

Postado em 21 abr 2009
Categoria(s) Ruby on Rails

Como todas as pessoas que procuram desenvolver com qualidade e agilidade, eu tive a minha saga até encontrar uma boa ferramenta de edição de código.

Eu só trabalho usando Linux, com certeza ele é o sistema operacional mais produtivo para trabalhar com desenvolvimento em tecnologias livres, para programar em PHP, Ruby on Rails, Java, Python e outras é uma maravilha. A quantidade de softwares e coisas legais é imensa.

Nessa minha saga e evolução no mundo dos editores/IDE já usei Dreamweaver, Gedit, Geany, Eclipse, Aptana, Komodo, Bluefish e por último o NetBeans. Sempre tinha alguns detalhes neles que acabava me irritando, algo que eles não conseguiam fazer. Alguns tinham tantos recursos que acabavam sendo pesados demais. Por último eu estava usando o NetBeans, ele tem umas sacadas legais e algumas coisas divertidas, mas é absurdamente pesado, outro detalhe é que algumas IDE’s tem a mania descontrolada de querer fazer tudo através de interface gráfica, trilhões de janelas para fazer coisas super simples, o terminal é um lance necessário em uma IDE, muitas coisas podem ser feitas em secundos através de um shell. Não a nada de errado em usar o shell, graças a ele que a produtividade aumenta muito, quem acha que interface gráfica aumenta a produtividade está enganado, as vezes ela só enrola mais as coisas.

Através de toda essa saga acima eu acabei chegando no VIM, usando especificamente o Gvim no Gnome para desenvolver em Ruby on Rails. Até o presente momento só são ótimas opiniões formadas sobre ele.

Nesse post vou mostrar como ganhar mais produtividade usando o Gvim.

Todos os passos abaixo foram feitos no Ubuntu 8.04, por que no Ubuntu? Porque ele é simples, tem uma porção de distribuições Linux por ae que complicam demais as coisas, o Ubuntu é sucesso porque é simples de usar. Existe uma grande chance de coisas simples fazerem mais sucesso que as coisas complicadas. :-)

Instalação do Gvim

1
sudo apt-get install vim vim-gnome vim-addon-manager vim-common vim-full vim-gtk vim-gui-common vim-rails vim-ruby vim-runtime vim-tiny exuberant-ctags ncurses-term

Instalação do Git

1
sudo apt-get install git

Instalação da gem para busca de arquivos

Essa gem está no github, desta forma é necessário adicionar o seu repositório: gem sources -a http://gems.github.com

1
sudo gem install jamis-fuzzy_file_finder

Instalação do pacote de configurações para o vim

Agora vamos instalar um pacote de configurações prontas para o vim, esse pacote foi criado pelo Fabio Akita, esse pacote já tem uma série de plugins, temas e snippets.

1
git clone git://github.com/akitaonrails/vimfiles.git ~/.vim

Você precisa criar o arquivo ~/.vimrc e adicionar o conteúdo abaixo:

1
2
3
4
5
6
7
source ~/.vim/vimrc
 
colorscheme vibrantink
set nu
set sts=2
set sw=2
let g:fuzzy_ignore = "gems/*"

Essas configurações irão fazer o número de linhas aparecer, ignorar os diretórios de gems e outros ajustes.

Os snippets estão em um repositório separado, desta forma precisamos obter esses arquivos, faça os passos abaixo:

1
2
3
cd ~/.vim
git submodule init
git submodule update

Existe um outro ajuste que pode ser feito, mas esse é opcional, da forma como está agora sempre irá aparecer um $ no final de cada linha, para marcar o fim, particularmente eu não gosto disso. Se você quiser é possível retirar essa marcação, edite o arquivo ~/.vim/vimrc procure pelas linhas:

1
2
"display tabs and trailing spaces
set list

E deixe a configuração set list comentada, desta forma:

1
2
"display tabs and trailing spaces
"set list

Feito isso nós já temos uma nova gama de funcionalidades adicionadas ao vim, mas é possível melhorar mais ainda, vamos agora instalar a fonte Monaco usada no TextMate. Essa fonte deixa o código com um visual legal.

Instalação da fonte Monaco

1
2
3
4
5
6
7
8
cd /usr/share/fonts/truetype
sudo mkdir myfonts
cd myfonts
sudo wget http://www.gringod.com/wp-upload/software/Fonts/Monaco_Linux.ttf
sudo chown root.root *.ttf
sudo mkfontdir
cd ..
fc-cache

Agora se você digitar no terminal:

1
gvim

Vai ver o gvim com a fonte Monaco e o tema desert.

Gvim

Com o gvim aberto vamos criar um projeto em Ruby on Rails, e ver as funcionalidades novas que temos no vim. Graças ao plugin rails.vim (http://rails.vim.tpope.net/) foram adicionadas uma série de features.

Criando um projeto Ruby on Rails

Digite no gvim:

1
tecla esc + :Rails autocomplete

Onde autocomplete é o nome da minha aplicação Ruby on Rails nesse exemplo.

A opção irá criar a aplicação com suporte ao banco de dados SQLite, se você quiser suporte ao outro banco de dados digite:

1
2
3
4
tecla esc + :Rails autocomplete -d mysql
ou
tecla esc + :Rails autocomplete -d postgresql
...

Esse comando irá criar uma aplicação Ruby on Rails nova.

Nova Aplicação

Pressione a tecla enter como informado na mensagem.

O plugin rails.vim é bem esperto, ele já vai abrir para você o database.yml para você configurar o banco de dados:

Database

Pressione a tecla i ou insert para editar os dados, faça as alterações necessárias e salve digitando:

1
tecla esc + :w

Uma breve descrição sobre as operações básicas do vim:

  • tecla esc + :w serve para salvar sua alteração (write)
  • tecla esc + :q serve para fechar o arquivo (quit)
  • tecla esc + :x serve para salvar e fechar o arquivo

Criando o banco de dados

1
tecla esc + :Rake db:create

DB Create

Pressione a tecla enter como informado na mensagem.

Criado um scaffold

1
tecla esc + :Rgenerate scaffold car name:string description:text color:string

Será gerado o scaffold para o model car, logo em seguida será exibido o cars_controller.rb:

Cars Controller

Rodando as migrações

1
tecla esc + :Rake db:migrate

Migrate

Visualizando a aplicação

Caso você queira visualizar aplicação nesse momento, você pode inicializar o servidor e ver um preview da aplicação rodando no navegador:

Inicializando o servidor

1
tecla esc + :Rserver

Servidor

Vendo preview no navegador

1
tecla esc + :Rpreview

Preview

Nesse momento o gvim ficará travado e o navegador será aberto para você visualizar o andamento do projeto, quando você fechar o navegador o gvim será destravado.

Navegador

Navegação de arquivos

Eu conheço duas formas de navegação de arquivos, a primeira é muito rápida:

1
tecla esc + ctrl + f

Busca arquivo

Digite o nome do arquivo desejado, por exemplo new:

Busca Arquivo New

A outra forma de navegação é em diretórios, digite:

1
tecla esc + :Vex

Vex

Snippets

Esse pacote que instalamos para o vim, tem muitos snippets já configurados para acelerar a condificação, eles podem ser encontrados no diretório ~/.vim/snippets:

Snippets

Se você olhar nesses diretórios vai poder descobrir as siglas para acessar o snippets, dê uma boa olhada e teste.

Snippets Ruby on Rails

Vamos testar um pouco os snippets, agora que você já sabe procurar arquivos, abra o arquivo car.rb:

1
2
3
tecla esc + ctrl + f
digite car.rb
enter

Model

Digite i ou insert para colocar o gvim em modo de edição e digite:

1
vp + tecla tab

Model vp

Model vp tab

Agora e só apertar tab e ir substituindo os valores.

Caso o snippet não funcione, feche o gvim, acesse o diretório da aplicação Ruby on Rails (autocomplete), estando dentro do diretório autocomplete abra o gvim, agora os snippets tem que funcionar.

A ideia desse post é apenas dar um visão geral, existe várias outras coisas possíveis de fazer, e muitos outros comandos poderosos para trabalhar com Ruby on Rails no vim, por isso eu sugiro que você leia esses outros artigos:

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

  • Share/Bookmark

Ruby on Rails como fazer dois atributos da mesma classe apontarem para a mesma classe pai no ActiveRecord

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

Hoje estava programando um sistema de menus, onde cada item de menu pode ter vários outros itens, não existindo limite de subníveis.

Para conseguir obter essa relação e associação no banco de dados criei dois models BackendMenu e BackendMenuNode, com as seguintes migrações:

BackendMenu:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class CreateBackendMenus < ActiveRecord::Migration
  def self.up
    create_table :backend_menus do |t|
      t.string  :title,     :null => false
      t.string  :path,      :null => false
      t.integer :weight,    :null => false, :default => 0
      t.boolean :is_active, :null => false, :default => false
      t.boolean :is_root,   :null => false, :default => false
      t.timestamps
    end
  end
 
  def self.down
    drop_table :backend_menus
  end
end

BackendMenuNode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class CreateBackendMenuNodes < ActiveRecord::Migration
  def self.up
    create_table :backend_menu_nodes do |t|
      t.integer :root_id, :null => false
      t.integer :node_id, :null => false
      t.integer :weight,  :null => false, :default => 0
    end
 
    add_index(:backend_menu_nodes, [:root_id, :node_id], :unique => true)
    execute "ALTER TABLE backend_menu_nodes ADD CONSTRAINT fk_backend_menu_nodes_backend_menus_root FOREIGN KEY (root_id) REFERENCES backend_menus (id) ON DELETE CASCADE ON UPDATE CASCADE"
    execute "ALTER TABLE backend_menu_nodes ADD CONSTRAINT fk_backend_menu_nodes_backend_menus_node FOREIGN KEY (node_id) REFERENCES backend_menus (id) ON DELETE CASCADE ON UPDATE CASCADE"
  end
 
  def self.down
    drop_table :backend_menu_nodes
  end
end

Todos os itens de menu vão ficar cadastrados na tabela backend_menus e associação para descobrir os menus filhos será feito pela tabela backend_menu_nodes. A tabela backend_menu_nodes tem as colunas root_id que se referência ao pai e a coluna node_id que se referência aos menus filhos, desta forma um menu pode ter N itens.

Tanto a coluna root_id e node_id fazem referência a tabela backend_menus.

Para conseguir obter essa associação no ActiveRecord fiz o seguinte:

BackendMenu:

1
2
3
4
5
class BackendMenu < ActiveRecord::Base
  # associações
  has_many :nodes, :class_name => "BackendMenuNode", :foreign_key => "root_id"
  ...
end

BackendMenuNode:

1
2
3
4
5
6
class BackendMenuNode < ActiveRecord::Base
  # associações
  belongs_to :root, :class_name => "BackendMenu", :foreign_key => "root_id"
  belongs_to :node, :class_name => "BackendMenu", :foreign_key => "node_id"
  ...
end

Fazendo a relação acima eu consigo navegar pelo menu pai e os meus filhos.

Para imprimir o menu eu criei 3 helpers usando a recursividade:

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
module BackendHelper
 
  # cria o menu do backend
  def menu(collection, class_name = "menu")
    content = content_tag :ul, :class => class_name do
      menu_items(collection)
    end
    content
  end
 
  # cria os items do menu
  def menu_items(collection)
    content = ""
    for item in collection
      if item.instance_of? BackendMenu
        content << item_nodes(item)
      else
        content << item_nodes(item.node)
      end
    end
    content
  end
 
  # cria os nós do item de menu
  def item_nodes(item)
    content = ""
    class_name = "leaf"
 
    if item.nodes.size > 0
      class_name = "collapsed"
      content << content_tag(:li, :class => class_name) do
        link_to(item.title, item.path) + menu(item.nodes, "menu hide")
      end
    else
      content << content_tag(:li, link_to(item.title, item.path), :class => class_name)
    end
    content
  end
 
end

No controlador eu faço o seguinte:

1
@backend_menus = BackendMenu.find :all, :conditions => { :is_root => true }, :order => 'weight'

Na view:

1
2
3
4
5
<!-- begin sidebar-left -->
<div id="sidebar-left">
  <%= menu(@backend_menus) %>
</div>
<!-- end sidebar-left -->

Se você quiser alguns menus de teste, usei a migração abaixo:

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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
class AddBackendMenus < ActiveRecord::Migration
  def self.up
    BackendMenu.delete_all
 
    # criação dos menus pais
    BackendMenu.create(:title => 'Principal',
      :path => 'principal',
      :weight => 1,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Criar Conteúdo',
      :path => 'criar-conteudo',
      :weight => 2,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Gerenciamento de Conteúdo',
      :path => 'gerenciamento-de-conteudo',
      :weight => 3,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Site Construtor',
      :path => 'site-construtor',
      :weight => 4,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Site Configuração',
      :path => 'site-configuracao',
      :weight => 5,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Gerenciamento de Usuário',
      :path => 'gerenciamento-de-usuario',
      :weight => 6,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Relatórios',
      :path => 'relatorios',
      :weight => 7,
      :is_active => true,
      :is_root => true)
 
    BackendMenu.create(:title => 'Ajuda',
      :path => 'ajuda',
      :weight => 8,
      :is_active => true,
      :is_root => true)
 
    # criação dos menus filhos
    BackendMenu.create(:title => 'Página',
      :path => 'criar-conteudo/pagina',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('criar-conteudo').id,
      :node_id => BackendMenu.find_by_path('criar-conteudo/pagina').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'História',
      :path => 'criar-conteudo/historia',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('criar-conteudo').id,
      :node_id => BackendMenu.find_by_path('criar-conteudo/historia').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Comentários',
      :path => 'gerenciamento-de-conteudo/comentarios',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Ativos',
      :path => 'gerenciamento-de-conteudo/comentarios/ativos',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios/ativos').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Teste',
      :path => 'gerenciamento-de-conteudo/comentarios/ativos/teste',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios/ativos').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios/ativos/teste').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Inativos',
      :path => 'gerenciamento-de-conteudo/comentarios/inativos',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/comentarios/inativos').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Conteúdo',
      :path => 'gerenciamento-de-conteudo/conteudo',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/conteudo').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Tipos de Conteúdo',
      :path => 'gerenciamento-de-conteudo/tipos-de-conteudo',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/tipos-de-conteudo').id,
      :weight => 3)
 
    BackendMenu.create(:title => 'Publicação de RSS',
      :path => 'gerenciamento-de-conteudo/publicacao-de-rss',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-conteudo').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-conteudo/publicacao-de-rss').id,
      :weight => 4)
 
    BackendMenu.create(:title => 'Blocos',
      :path => 'site-construtor/blocos',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/blocos').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Formulários',
      :path => 'site-construtor/formularios',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/formularios').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Menus',
      :path => 'site-construtor/menus',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/menus').id,
      :weight => 3)
 
    BackendMenu.create(:title => 'Módulos',
      :path => 'site-construtor/modulos',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/modulos').id,
      :weight => 4)
 
    BackendMenu.create(:title => 'temas',
      :path => 'site-construtor/temas',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/temas').id,
      :weight => 5)
 
    BackendMenu.create(:title => 'Tradução',
      :path => 'site-construtor/traducao',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-construtor').id,
      :node_id => BackendMenu.find_by_path('site-construtor/traducao').id,
      :weight => 6)
 
    BackendMenu.create(:title => 'Idiomas',
      :path => 'site-configuracao/idiomas',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-configuracao').id,
      :node_id => BackendMenu.find_by_path('site-configuracao/idiomas').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Logs e Alertas',
      :path => 'site-configuracao/logs-e-alertas',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-configuracao').id,
      :node_id => BackendMenu.find_by_path('site-configuracao/logs-e-alertas').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Manutenção do Site',
      :path => 'site-configuracao/manuencao-do-site',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-configuracao').id,
      :node_id => BackendMenu.find_by_path('site-configuracao/manuencao-do-site').id,
      :weight => 3)
 
    BackendMenu.create(:title => 'Ações',
      :path => 'site-configuracao/acoes',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('site-configuracao').id,
      :node_id => BackendMenu.find_by_path('site-configuracao/acoes').id,
      :weight => 4)
 
    BackendMenu.create(:title => 'Regras de Acesso',
      :path => 'gerenciamento-de-usuario/regras-de-acesso',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/regras-de-acesso').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Permissões',
      :path => 'gerenciamento-de-usuario/permissoes',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/permissoes').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Regras',
      :path => 'gerenciamento-de-usuario/regras',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/regras').id,
      :weight => 3)
 
    BackendMenu.create(:title => 'Configurações de Usuários',
      :path => 'gerenciamento-de-usuario/configuracoes-de-usuarios',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/configuracoes-de-usuarios').id,
      :weight => 4)
 
    BackendMenu.create(:title => 'Usuários',
      :path => 'gerenciamento-de-usuario/usuarios',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('gerenciamento-de-usuario').id,
      :node_id => BackendMenu.find_by_path('gerenciamento-de-usuario/usuarios').id,
      :weight => 5)
 
    BackendMenu.create(:title => 'Entrada de Logs',
      :path => 'relatorios/entrada-de-logs',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('relatorios').id,
      :node_id => BackendMenu.find_by_path('relatorios/entrada-de-logs').id,
      :weight => 1)
 
    BackendMenu.create(:title => 'Erros de Acesso Negado',
      :path => 'relatorios/erros-de-acesso-negado',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('relatorios').id,
      :node_id => BackendMenu.find_by_path('relatorios/erros-de-acesso-negado').id,
      :weight => 2)
 
    BackendMenu.create(:title => 'Status',
      :path => 'relatorios/status',
      :is_active => true,
      :is_root => false)
    BackendMenuNode.create(:root_id => BackendMenu.find_by_path('relatorios').id,
      :node_id => BackendMenu.find_by_path('relatorios/status').id,
      :weight => 3)
  end
 
  def self.down
    BackendMenu.delete_all
  end
end

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

  • Share/Bookmark