Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

View fdutey's full-sized avatar

Florian Dutey fdutey

  • Simfinity
  • Zhuhai
View GitHub Profile
class Bookmark < ActiveRecord::Base
#Validations
validates_presence_of :label
validates_presence_of :url
def clean_url
url =~ /^http:\/\//i ? url : "http://#{url}"
end
end
module ActionView
module Helpers
class InstanceTag
def to_label_tag(text = nil, options = {})
options = options.stringify_keys
name_and_id = options.dup
add_default_name_and_id(name_and_id)
options.delete("index")
options["for"] ||= name_and_id["id"]
if text.blank?
#Questions mark (points d'interrogation)
Foo.all(:conditions => ['foo = ? AND bar = ?', foo, bar])
#Hash and keys (méthode alternative, un hash et des clefs)
Foo.all(:conditions => ['foo = :foo AND bar = :bar', params])
#params => { :foo => 'bar', :bar => 'foo', ... }
h = { "a" => 1, "b" => 2, "c" => 3 }
h.collect #=> [["a", 1], ["b", 2], ["c", 3]]
h = { "a" => 1, "b" => 2, "c" => 3 }
#La syntaxe de Ruby permet ceci
a, b = ["a", "b"]
a #=> "a"
b #=> "b"
#N'avons nous pas dit qu'un Hash était un tableau de tableaux?
h.each{ |obj| puts obj.class } #=> Array \n Array
posts = Post.all #=> 3 posts, 2 publiés, un non
#indique si TOUS les éléments d'un enumerable obéissent à une condition passée sous forme de bloc
posts.all?{ |post| post.published? } #=> false
#indique si au moins 1 élement de la collection obéit à une condition passée sous forme de bloc
posts.any?{ |post| post.published? } #=> true
#renvoie un tableau contenant la valeur renvoyée par un bloc pour chaque élément de la collection
posts.collect{ |post| post.published? } #=> [true, true, false]
#Je reprends l'exemple du post précédent
posts = Post.all
posts.collect{ |post| post.published? } #=> [true, true, false]
posts.collect(&:published?) #=> [true, true, false]
posts = Post.all
#renvoie true si ma collection a plusieurs (> 1) élément répondant à la condition passée sous forme de bloc
posts.many?(&:published?) #=> true
#renvoie true si aucun élément de ma collection ne répond à la condition passée sous forme de bloc
posts.none?(&:published?) #=> false
#effectue la somme des valeurs renvoyées successivement par un bloc executé sur chaque élément de ma collection
posts.sum(&:comments_count) #=> 10
class Object
def with(obj, &block)
obj.instance_eval &block
end
end
h = { :a => 1, :b => 2 }
a = ["a", "b"]
with h do
a = { :a => '1', :b => '2' }
b = a.dup
with a do
def test_method
keys
end
end
a.test_method #=> [:b, :a]