Postado em 24 jun 2009
Categoria(s) Ruby
Uma forma simples de gerar strings randômicas alfanuméricas no Ruby é o código abaixo:
def random_alphanumeric(size=6)
chars = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a
(0...size).collect { chars[Kernel.rand(chars.length)] }.join
end
Se você gostou desse texto e acha que ajudou você, me recomende:
.
Tags:
$A,
0,
9,
alfanumérica,
alphanumeric,
chars,
código,
collect,
exemplo,
forma,
generate,
gerar,
join,
Kernel,
length,
rand,
random,
randômica,
random_alphanumeric,
Ruby,
simples,
size,
string,
to_a,
z
No Ruby existe o método public_methods ele retorna todos os métodos públicos de um objeto. Você pode usar ele junto com o método debug.
Exemplo:
1
2
3
4
5
| ...
<% if @drafts.size > 0 %>
<% @drafts.each do |draft| %>
<%= debug(draft.public_methods) %>
... |
Isso irá produzir a saída 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
| ---
- save_without_validation
- destroy_without_transactions
- validate_associated_records_for_photos
- silence_stream
- reject_new_nested_attributes_procs
- save_with_dirty!
- extend_with_included_modules_from
- marked_for_destruction?
- update_attributes!
- autosave_associated_records_for_user
- methods
- send
- has_attribute?
- destroy_without_callbacks
- connection_handler
- taint
- to_enum
- instance_variable_defined?
- encode64
- write_attribute
- after_validation_on_create
- save_with_transactions
- connection
- table_name_prefix
- write_attribute_without_dirty
- require_or_load
- save_without_dirty!
- increment!
- validate_associated_records_for_user
- reload_with_dirty
- singleton_methods
- instance_eval
- time_zone_aware_attributes
- changed?
- decrement
- schema_format
- debugger
- returning
- lock!
- valid?
- enum_for
- subclasses_of
- metaclass
- before_validation_on_update
- nil?
- to_xml
- reload
- decode64
- before_update
- videos
- unserializable_attribute?
- reload_without_dirty
- protected_methods
- instance_exec
- readonly?
- unserialize_attribute
- from_json
- default_timezone
- tainted?
- videos=
- before_save
- breakpoint
- changed
- rollback_active_record_state!
- untaint
- instance_of?
- with_options
- after_validation_on_update
- equal?
- save_without_transactions
- table_name_suffix
- suppress
- require_association
- taguri
- readonly!
- decode_b
- decrement!
- respond_to_without_attributes?
- column_for_attribute
- after_update
- photos
- blank?
- hash
- private_methods
- daemonize
- taguri=
- toggle
- locking_enabled?
- attribute_names
- `
- after_save
- save!
- photos=
- timestamped_migrations
- partial_updates?
- to_json
- changes
- kind_of?
- reload_with_autosave_associations
- freeze
- store_full_sti_class?
- eql?
- to_yaml_style
- present?
- instance_values
- id
- destroy_without_lock
- public_methods
- method_missing
- id=
- valid_with_callbacks?
- save_with_transactions!
- is_a?
- require
- becomes
- pluralize_table_names
- video_ids
- require_library_or_gem
- tap
- load_with_new_constant_marking
- dclone
- cache_key
- _delete
- attributes_before_type_cast
- type
- instance_variable_names
- toggle!
- save
- to_yaml
- video_ids=
- to_param
- transaction
- instance_variables
- to_yaml_properties
- loaded_user?
- query_attribute
- clear_aggregation_cache
- __id__
- require_dependency
- save_with_validation!
- from_xml
- frozen?
- valid_without_callbacks?
- store_full_sti_class
- acts_like?
- record_timestamps
- save_with_dirty
- save_without_transactions!
- set_user_target
- to_a
- reload_without_autosave_associations
- before_destroy
- display
- respond_to?
- autosave_associated_records_for_videos
- attribute_types_cached_by_default
- method
- attribute_for_inspect
- class
- copy_instance_variables_from
- id_before_type_cast
- before_validation
- to_query
- photo_ids
- configurations
- destroy_with_transactions
- enable_warnings
- instance_variable_get
- invalid?
- clear_association_cache
- __send__
- save_without_validation!
- default_scoping
- ==
- before_create
- ===
- extend
- save_without_dirty
- build_user
- photo_ids=
- to_s
- unloadable
- run_callbacks
- update_attribute
- after_destroy
- update_attributes
- mark_for_destruction
- duplicable?
- colorize_logging
- validate_associated_records_for_videos
- skip_time_zone_conversion_for_attributes
- silence_warnings
- attributes
- increment
- b64encode
- read_attribute_before_type_cast
- clone
- after_validation
- save_with_validation
- errors
- with_transaction_returning_status
- user
- primary_key_prefix_type
- autosave_associated_records_for_photos
- silence_stderr
- =~
- instance_variable_set
- read_attribute
- attributes=
- try
- extended_by
- new_record?
- after_create
- user=
- create_user
- destroy_with_callbacks
- destroy
- attribute_present?
- include_root_in_json
- inspect
- "[]"
- class_eval
- lock_optimistically
- partial_updates
- delete
- logger
- "[]="
- dup
- object_id
- remove_subclasses_of
- quoted_id
- before_validation_on_create |
Se você gostou desse texto e acha que ajudou você, me recomende:
.
Tags:
debug,
descobrir,
drafts,
each,
exemplo,
if,
métodos,
objeto,
output,
públicos,
public_methods,
rails,
Ruby,
Ruby on Rails,
size
No Ruby existe o método debug, com ele você pode debugar uma variável e visualizar todos os parâmetros.
Exemplo:
1
2
3
4
5
| ...
<% if @drafts.size > 0 %>
<% @drafts.each do |draft| %>
<%= debug(draft) %>
... |
Esse exemplo irá gerar a seguinte saída:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| --- !ruby/object:Message
attributes:
step: "1"
created_at: 2009-06-04 20:11:21
title: Legal
updated_at: 2009-06-10 18:25:51
id: "1"
user_id: "1"
content: |-
<p>Vamos testar</p>
<p>Legal para carambaaa</p>
<p>Vamos atualizar as informações.....</p>
send_date:
attributes_cache: {} |
Essa é uma dica simples, mas que pode ajudar bastante.
Se você gostou desse texto e acha que ajudou você, me recomende:
.
Tags:
attributes,
attributes_cache,
debug,
debugando,
do,
drafts,
each,
exemplo,
if,
message,
método,
object,
parâmetros,
rails,
Ruby,
Ruby on Rails,
size,
variáveis,
variável
Estou desenvolvendo uma aplicação em rails, hoje surgiu a necessidade de criar a navegação por breadcrumb. Fui atrás para ver o que já existia em Rails, infelizmente encontrei algumas coisas complexas e estourando o escopo da minha minha necessidade. Na verdade o que eu precisava era criar links e algumas vezes somente aparecer o texto sem link no breadcrumb.
Em vez de perder um tempão na internet fuçando, decidi fazer um helper para gerar o breadcrumb conforme a minha necessidade.
Fiz o seguinte, no application_helper.rb criei o método breadcrumb:
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
| # Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def breadcrumb(array)
output = '
<div class="breadcrumb">'
size = array.size - 1
array.each {
|e| e.each {
|key, value|
if value.empty?
output += key
else
output += link_to(key, value)
end
output += " > " if size > 0
}
size -= 1
}
output += '</div>
'
return output
end
end |
No meu template eu chamo o helper breadcrumb passando um array e em cada posição do array um hash separado pela chave e valor, onde a chave é o texto e o valor é o link. Caso no valor eu passe uma string vazia ”, apenas é colocado o texto no breadcrumb.
Exemplo no template show.rhtml:
1
| <%= breadcrumb([{ 'Home' => home_url }, { 'Notícias' => url_for(:controller => :histories) }, { @history.title => '' }]) %> |
Que vai gerar o seguinte html:
1
| <a href="http://localhost:3000/">Home</a> > <a href="/histories">Notícias</a> > Governo Federal qualifica a gestão da área de Tecnologia da Informação |
Outro exemplo mais simples:
1
2
3
| <%= breadcrumb([{ 'Home' => 'http://patrickespake.wordpress.com' }, { 'Tags' => 'http://patrickespake.wordpress.com/tags') }, { 'Ruby on Rails' => '' }]) %>
<%= breadcrumb([{ 'Home' => 'http://patrickespake.wordpress.com' }, { 'Tags' => 'http://patrickespake.wordpress.com/tags') }]) %> |
Se você gostou desse texto e acha que ajudou você, me recomende:
.
Tags:
aplicação,
app,
application_helper.rb,
array,
breadcrumb,
dev,
each,
hash,
helper,
html,
if,
key,
link_to,
output,
rails,
return,
Ruby,
Ruby on Rails,
show,
size,
sourcecode,
value