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
140
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
71
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
260
Zero-downtime payment platforms
sikachu
1
120
Other Decks in Programming
See All in Programming
NANIMACHI
naokiito
0
940
The Efficiency Paradox and How to Save Yourself and the World
hollycummins
0
160
AWS認定資格を受験するにあたり、気づいたこと・実践していたことのまとめ
satoshi256kbyte
1
120
"noncopyable types" の使いどころについて考えてみた
andpad
0
140
(Deep|Web) Link support with expo-router
mrtry
0
170
perl for shell, awk and sed programmers
mackee
1
670
ビット演算の話 / Let's play with bit operations
kaityo256
PRO
4
170
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
8
410
Vue :: Better Testing 2024
up1
1
400
フロントエンドの現在地とこれから
koba04
10
4.5k
データサイエンスのフルサイクル開発を実現する機械学習パイプライン
xcnkx
2
500
利用者視点で考える、イテレータとの上手な付き合い方
syumai
4
230
Featured
See All Featured
Web Components: a chance to create the future
zenorocha
310
42k
What's in a price? How to price your products and services
michaelherold
243
11k
Docker and Python
trallard
40
3k
Large-scale JavaScript Application Architecture
addyosmani
510
110k
Into the Great Unknown - MozCon
thekraken
30
1.4k
Done Done
chrislema
181
16k
GitHub's CSS Performance
jonrohan
1030
450k
BBQ
matthewcrist
85
9.2k
Pencils Down: Stop Designing & Start Developing
hursman
119
11k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
Unsuck your backbone
ammeep
668
57k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
92
16k
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