Posts Tagged ‘public_methods’

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

Ruby on Rails debug para descobrir todos os métodos públicos de um objeto

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

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: Recommend Me.

  • Share/Bookmark