Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Introduction to Active Support
Search
Prem Sichanugrist
June 20, 2014
Programming
0
150
Introduction to Active Support
Presented for Metis students a thoughtbot office
Prem Sichanugrist
June 20, 2014
Tweet
Share
More Decks by Prem Sichanugrist
See All by Prem Sichanugrist
Working with Huge Databases and Tables
sikachu
1
73
What's coming in Rails 5.2, and sneak peek into Rails 6
sikachu
6
5.9k
Testing Any Website Written in Any Language With Capybara and RSpec
sikachu
1
150
Zero-downtime payment platforms
sikachu
2
230
Hidden gems in Ruby on Rails
sikachu
5
250
Active Support Secrets
sikachu
1
240
Dependencies Testing With Appraisal And Bundler
sikachu
1
230
You have to test multiple versions of your gem's dependencies. You used Appraisal. It's super affective!
sikachu
0
270
Zero-downtime payment platforms
sikachu
1
120
Other Decks in Programming
See All in Programming
LLM生成文章の精度評価自動化とプロンプトチューニングの効率化について
layerx
PRO
2
140
Vitest Browser Mode への期待 / Vitest Browser Mode
odanado
PRO
2
2.1k
GitHub Actionsのキャッシュと手を挙げることの大切さとそれに必要なこと
satoshi256kbyte
5
390
Kotlin2でdataクラスの copyメソッドを禁止する/Data class copy function to have the same visibility as constructor
eichisanden
1
140
デプロイを任されたので、教わった通りにデプロイしたら障害になった件 ~俺のやらかしを越えてゆけ~
techouse
52
32k
CPython 인터프리터 구조 파헤치기 - PyCon Korea 24
kennethanceyer
0
250
カラム追加で増えるActiveRecordのメモリサイズ イメージできますか?
asayamakk
4
1.6k
Universal Linksの実装方法と陥りがちな罠
kaitokudou
1
220
詳細解説! ArrayListの仕組みと実装
yujisoftware
0
490
とにかくAWS GameDay!AWSは世界の共通言語! / Anyway, AWS GameDay! AWS is the world's lingua franca!
seike460
PRO
1
570
Dev ContainersとGitHub Codespacesの素敵な関係
ymd65536
1
130
CSC305 Lecture 13
javiergs
PRO
0
130
Featured
See All Featured
Making the Leap to Tech Lead
cromwellryan
133
8.9k
Unsuck your backbone
ammeep
668
57k
Stop Working from a Prison Cell
hatefulcrawdad
267
20k
The Cost Of JavaScript in 2023
addyosmani
45
6.6k
Teambox: Starting and Learning
jrom
132
8.7k
Fontdeck: Realign not Redesign
paulrobertlloyd
81
5.2k
Code Reviewing Like a Champion
maltzj
519
39k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
43
6.6k
Writing Fast Ruby
sferik
626
61k
Raft: Consensus for Rubyists
vanstee
136
6.6k
Rails Girls Zürich Keynote
gr2m
93
13k
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
47
5k
Transcript
Introduction to Active Support
Notations $ irb # Shell command > str = "Hello
World" # Ruby code #=> Hello World # Return value
Notations Object.method <= Class method Object#method <= Instance method
What is Active Support?
"Utility classes and Ruby extensions from Rails" (From https://github.com/rails/rails/tree/master/activesupport)
Utility Classes • ActiveSupport::Callbacks • ActiveSupport::HashWithIndifferentAccess • ActiveSupport::MessageEncrypter • ActiveSupport::MessageVerifier
• ... etc ...
Ruby Extensions • object.present? / object.blank? • date.yesterday / date.tomorrow
• 1.day.ago / 2.months.from_now • ... etc ...
Part of Rails framework Available to be used inside Rails
# To use outside Rails $ gem install activesupport #
in Ruby > require "activesupport/all"
Digging Deeper
Callbacks
Callbacks • Helpers to define and run callbacks • Use
in Active Record, Action Pack, etc. • before_action, after_action, before_save, etc.
Callback Example class User < ActiveRecord::Base before_save :do_something def do_something
# ... end end
Callback Example class Account include ActiveSupport::Callbacks define_callbacks :save set_callback :save,
:before, :do_something def save run_callbacks :save do # ... end end def do_something # ... end end
MessageEncrypter Encrypts message with a key
MessageEncrypter > salt = SecureRandom.random_bytes(64) > key = ActiveSupport::KeyGenerator. new('password').generate_key(salt)
> crypt = ActiveSupport::MessageEncryptor.new(key) > encrypted_data = crypt. encrypt_and_sign('my secret data') > crypt.decrypt_and_verify(encrypted_data)
Notifications
Notifications • Uses for logging purposes • Executer instrument an
event that should be subscribed to: • Action View's "render" • Active Record's "execute SQL" • etc. • Listeners subscribe to those events from another part of the application
TimeZone
TimeZone • Contains full mapping of time zones • Perform
time zone conversions
TimeZone > ActiveSupport::TimeZone.all > ActiveSupport::TimeZone.us_zones > Time.zone = "America/New_York" >
time = Time.zone.now #=> "Fri, 20 Jun 2014 14:35:00 EDT -04:00" > time.in_time_zone("America/Los_Angeles") #=> "Fri, 20 Jun 2014 11:35:00 PDT -07:00"
Core Extensions
Array
Array#from Array#to
Array#from Array#to > array = [1, 2, 3, 4] >
array.from(2) #=> [3, 4] > array.to(2) #=> [1,2,3]
Array#second Array#third Array#fourth Array#fifth Array#forty_two
Array Access > array = (1..100).to_a > array.first #=> 1
> array.second #=> 2 > array.third #=> 3 > array.fourth #=> 4 > array.fifth #=> 5 > array.forty_two #=> 42
Array#to_sentence
Array#to_sentence > fruits = %w(banana strawberry kiwi) > fruits.to_sentence #=>
"banana, strawberry, and kiwi > sports = %w(football baseball) > sports.to_sentence #=> "football and baseball"
Array#in_groups_of Array#in_groups
Array#in_group_of > array = (1..10).to_a > array.in_group_of(3) # => [[1,
2, 3], [4, 5, 6], [7, 8, 9], [10, nil, nil]]
Array#in_groups > array = (1..10).to_a > array.in_groups(3) #=> [[1, 2,
3, 4], [5, 6, 7, nil], [8, 9, 10, nil]]
Date, Time, DateTime
Date.current Date.yesterday Date.tomorrow
Time#beginning_of_day Time#middle_of_day Time#end_of_day
Time#beginning_of_hour Time#end_of_hour
Time#all_day Date#all_week Date#all_month Date#all_year
Time#today? Time#past? Time#future?
Hash
Hash#deep_merge
Hash#deep_merge > h1 = { a: true, b: { c:
[1, 2, 3] } } > h2 = { a: false, b: { x: [3, 4, 5] } } > h1.deep_merge(h2) #=> { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } }
Hash#except
Hash#except > hash = { one: 1, two: 2 }
> hash.except(:one) #=> { two: 2 }
Hash#with_indifferent_access
# In Controller > params[:id] #=> 1 > params['id'] #=>
1 > params.class #=> ActiveSupport::HashWithIndifferentAccess
Hash#with_indifferent_access > hash = { one: 1 }.with_indifferent_access > hash[:one]
#=> 1 > hash['one'] #=> 1
Hash#stringify_keys Hash#symbolize_keys
Hash#stringify_keys Hash#symbolize_keys > hash = { one: 1, 'two' =>
2 } > hash.stringify_keys #=> { 'one' => 1, 'two' => 2 } > hash.symbolize_keys #=> { one: 1, two: 2 }
Hash#reverse_merge
Hash#reverse_merge > h1 = { one: 'one' } > h2
= { one: 'uno', two: 'dos' } > h1.merge(h2) #=> { one: 'uno', two: 'dos' } > h1.reverse_merge(h2) #=> { one: 'one', two: 'dos' }
Hash#slice
Hash#slice > hash = { one: 1, two: 2, three:
3 } > hash.slice(:one, :two) #=> { one: 1, two: 2 }
Integer
Integer#ordinalize
Integer#ordinalize > 1.ordinalize #=> "1st" > 2.ordinalize #=> "2nd"
Integer#ordinal
Integer#ordinalize > 1.ordinal #=> "st" > 2.ordinalize #=> "nd"
Integer#days Integer#months Integers#years
Examples > 1.month.ago > 1.month.from_now > 1.month.since(time) > 1.year.from(time)
Object
Object#present? Object#blank?
Object#try
Object#try > user = nil > user.name #=> NoMethodError >
user.try(:name) #=> nil
Object#presence
Object#presence > name = "John" > puts "Hello #{name}" #=>
"Hello John"
Object#presence > name = "" > puts "Hello #{name}" #=>
"Hello "
Object#presence > name = "" > puts "Hello #{name.present? ?
name : "Guest"}" #=> "Hello Guest"
Object#presence > name = "" > puts "Hello #{name.presence ||
"Guest"}" #=> "Hello Guest"
String
String#to_time String#to_date String#to_datetime
String#to_time String#to_date String#to_datetime > "13-12-2012".to_time #=> 2012-12-13 00:00:00 -0500 >
"1-1-2012".to_date #=> Sun, 01 Jan 2012 > "1-1-2012".to_datetime #=> Sun, 01 Jan 2012 00:00:00 +0000
String#truncate
String#truncate > "Hello World".truncate(8) #=> "Hello Wo..."
String#singularize String#pluralize String#camelize String#titleize String#humanize
Inflections Example > "man".pluralize #=> "men" > "octopi".singularize #=> "octopus"
> "user_name".camelize #=> "UserName" > "hello world".titlize #=> "Hello World" > "full_name".humanize #=> "Full name"
String#inquiry
String#inquiry > color = "red".inquiry > color.red? #=> true >
color.blue? #=> false > Rails.env.development?
http://guides.rubyonrails.org/active_support_core_extensions.html