SlideShare uma empresa Scribd logo
1 de 19
Baixar para ler offline
Active Support
Core Extensions (3)
ROR lab. DD-1
- The 3rd round -
April 13, 2013
Hyoseong Choi
Ext. to Class
• class_attribute
active_support/core_ext/class/
attribute.rb
class A
  class_attribute :x
end
 
class B < A; end
 
class C < B; end
 
A.x = :a
B.x # => :a
C.x # => :a
B.x = :b
A.x # => :a
C.x # => :b
 
C.x = :c
A.x # => :a
B.x # => :b
one or more inheritable class attributes that can be overridden at any level down the hierarchy
Ext. to Class
• class_inheritable_accessor, _reader, _writer
active_support/core_ext/class/
inheritable_attributes.rb
module ActionController
  class Base
    # FIXME: REVISE/SIMPLIFY THIS COMMENT.
    # The value of allow_forgery_protection is inherited,
    # but its value in a particular class does not affect
    # the value in the rest of the controllers hierarchy.
    class_inheritable_accessor :allow_forgery_protection
  end
end
: deprecated ➜ class_attribute instead
accessors for class-level data which is inherited but not shared with children
class C; end
C.subclasses # => []
 
class B < C; end
C.subclasses # => [B]
 
class A < B; end
C.subclasses # => [B]
 
class D < C; end
C.subclasses # => [B, D]
Ext. to Class
• subclasses
active_support/core_ext/class/
subclasses.rb
C
B
A
D
Ext. to Class
• descendants
active_support/core_ext/class/
subclasses.rb
class C; end
C.descendants # => []
 
class B < C; end
C.descendants # => [B]
 
class A < B; end
C.descendants # => [B, A]
 
class D < C; end
C.descendants # => [B, A, D]
C
B
A
D
Ext. to String
• Strings “(html) unsafe” by default since Rails3
"".html_safe? # => false
s = "".html_safe
s.html_safe? # => true
• html_safe no escaping
s = "<script>...</script>".html_safe
s.html_safe? # => true
s            # => "<script>...</script>"
active_support/core_ext/string/
output_safety.rb
Ext. to String
• html_safe
active_support/core_ext/string/
output_safety.rb
<%= raw @cms.current_template %>
<%== @cms.current_template %>
def raw(stringish)
  stringish.to_s.html_safe
end
Ext. to String
• squish, squish!
active_support/core_ext/string/
filters.rb
" n  foonr t bar n".squish # => "foo bar"
Ext. to String
• truncate
active_support/core_ext/string/
filters.rb
"Oh dear! Oh dear! I shall be late!".truncate(20)
# => "Oh dear! Oh dear!..."
"Oh dear! Oh dear! I shall be
late!".truncate(20, :omission => '&hellip;')
# => "Oh dear! Oh &hellip;" …
"Oh dear! Oh dear! I shall be late!".truncate(18)
# => "Oh dear! Oh dea..."
"Oh dear! Oh dear! I shall be
late!".truncate(18, :separator => ' ')
# => "Oh dear! Oh..."
Ext. to String
• Output safety - inquiry
active_support/core_ext/string/
inquiry.rb
"production".inquiry.production? # => true
"active".inquiry.inactive?       # => false
a StringInquirer
object
Ext. to String
• Output safety - Key-based interpolation
active_support/core_ext/string/
interpolation.rb
"Total is %<total>.02f" % {:total => 43.1} 
# => Total is 43.10
"I say %{foo}" % {:foo => "wadus"}         
# => "I say wadus"
"I say %{woo}" % {:foo => "wadus"}         
# => KeyError
Ext. to String
• Output safety - start_with? / ends_with?
active_support/core_ext/string/
starts_ends_with.rb
"foo".starts_with?("f") # => true
"foo".ends_with?("o")   # => true
Ext. to String
• Output safety - strip_heredoc
active_support/core_ext/string/
strip.rb
if options[:usage]
  puts <<-USAGE.strip_heredoc
    This command does such and such.
 
    Supported options are:
      -h         This message
      ...
  USAGE
end
Ext. to String
• Access - at(position)
active_support/core_ext/string/
access.rb
"hello".at(0)  # => "h"
"hello".at(4)  # => "o"
"hello".at(-1) # => "o"
"hello".at(10) # => ERROR if < 1.9, nil in 1.9
Ext. to String
• Access - from(position)
active_support/core_ext/string/
access.rb
"hello".from(0)  # => "hello"
"hello".from(2)  # => "llo"
"hello".from(-2) # => "lo"
"hello".from(10) # => "" if < 1.9, nil in 1.9
Ext. to String
• Access - to(position)
active_support/core_ext/string/
access.rb
"hello".to(0)  # => "h"
"hello".to(2)  # => "hel"
"hello".to(-2) # => "hell"
"hello".to(10) # => "hello"
Ext. to String
• Access - first/last
active_support/core_ext/string/
access.rb
str.first(n) or str.to(n-1)
str.last(n) or str.from(-n)
Ext. to String
• Inflections
active_support/core_ext/string/
inflections.rb
• pluralize
• singularize
• camerlize
• underscore
• titleize
• dasherize
• demodulize
• deconstantize
• parameterize
• tableize
• classify
• constantize
• humanize
• foreign_key
ROR Lab.
감사합니다.

Mais conteúdo relacionado

Semelhante a Active Support Core Extension (3)

Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
mircodotta
 
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia KazakovaC++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
corehard_by
 
Fuzzing - A Tale of Two Cultures
Fuzzing - A Tale of Two CulturesFuzzing - A Tale of Two Cultures
Fuzzing - A Tale of Two Cultures
CISPA Helmholtz Center for Information Security
 

Semelhante a Active Support Core Extension (3) (20)

Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is Awesome
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Software Environmentalism (ECOOP 2014 Keynote)
Software Environmentalism (ECOOP 2014 Keynote)Software Environmentalism (ECOOP 2014 Keynote)
Software Environmentalism (ECOOP 2014 Keynote)
 
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia KazakovaC++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
Machine learning on source code
Machine learning on source codeMachine learning on source code
Machine learning on source code
 
Using spl tools in your code
Using spl tools in your codeUsing spl tools in your code
Using spl tools in your code
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
GCRC 2014 - The Dark Side of Ruby
GCRC 2014 - The Dark Side of RubyGCRC 2014 - The Dark Side of Ruby
GCRC 2014 - The Dark Side of Ruby
 
Presentation on Polymorphism (SDS).ppt
Presentation on Polymorphism (SDS).pptPresentation on Polymorphism (SDS).ppt
Presentation on Polymorphism (SDS).ppt
 
Secure Programming Practices in C++ (NDC Oslo 2018)
Secure Programming Practices in C++ (NDC Oslo 2018)Secure Programming Practices in C++ (NDC Oslo 2018)
Secure Programming Practices in C++ (NDC Oslo 2018)
 
Storage class
Storage classStorage class
Storage class
 
Fuzzing - A Tale of Two Cultures
Fuzzing - A Tale of Two CulturesFuzzing - A Tale of Two Cultures
Fuzzing - A Tale of Two Cultures
 
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek PiotrowskiJDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
 
Asciidoctor New, Noteworthy and Beyond Devoxx-2017
Asciidoctor New, Noteworthy and Beyond Devoxx-2017Asciidoctor New, Noteworthy and Beyond Devoxx-2017
Asciidoctor New, Noteworthy and Beyond Devoxx-2017
 
Unit v
Unit vUnit v
Unit v
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 

Mais de RORLAB

Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
RORLAB
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
RORLAB
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
RORLAB
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
RORLAB
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
RORLAB
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
RORLAB
 

Mais de RORLAB (20)

Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record association
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on Rails
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2
 
ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2
 
Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2
 
Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2
 
Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2
 
Routing 2, Season 1
Routing 2, Season 1Routing 2, Season 1
Routing 2, Season 1
 
Routing 1, Season 1
Routing 1, Season 1Routing 1, Season 1
Routing 1, Season 1
 

Último

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Último (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 

Active Support Core Extension (3)

  • 1. Active Support Core Extensions (3) ROR lab. DD-1 - The 3rd round - April 13, 2013 Hyoseong Choi
  • 2. Ext. to Class • class_attribute active_support/core_ext/class/ attribute.rb class A   class_attribute :x end   class B < A; end   class C < B; end   A.x = :a B.x # => :a C.x # => :a B.x = :b A.x # => :a C.x # => :b   C.x = :c A.x # => :a B.x # => :b one or more inheritable class attributes that can be overridden at any level down the hierarchy
  • 3. Ext. to Class • class_inheritable_accessor, _reader, _writer active_support/core_ext/class/ inheritable_attributes.rb module ActionController   class Base     # FIXME: REVISE/SIMPLIFY THIS COMMENT.     # The value of allow_forgery_protection is inherited,     # but its value in a particular class does not affect     # the value in the rest of the controllers hierarchy.     class_inheritable_accessor :allow_forgery_protection   end end : deprecated ➜ class_attribute instead accessors for class-level data which is inherited but not shared with children
  • 4. class C; end C.subclasses # => []   class B < C; end C.subclasses # => [B]   class A < B; end C.subclasses # => [B]   class D < C; end C.subclasses # => [B, D] Ext. to Class • subclasses active_support/core_ext/class/ subclasses.rb C B A D
  • 5. Ext. to Class • descendants active_support/core_ext/class/ subclasses.rb class C; end C.descendants # => []   class B < C; end C.descendants # => [B]   class A < B; end C.descendants # => [B, A]   class D < C; end C.descendants # => [B, A, D] C B A D
  • 6. Ext. to String • Strings “(html) unsafe” by default since Rails3 "".html_safe? # => false s = "".html_safe s.html_safe? # => true • html_safe no escaping s = "<script>...</script>".html_safe s.html_safe? # => true s            # => "<script>...</script>" active_support/core_ext/string/ output_safety.rb
  • 7. Ext. to String • html_safe active_support/core_ext/string/ output_safety.rb <%= raw @cms.current_template %> <%== @cms.current_template %> def raw(stringish)   stringish.to_s.html_safe end
  • 8. Ext. to String • squish, squish! active_support/core_ext/string/ filters.rb " n  foonr t bar n".squish # => "foo bar"
  • 9. Ext. to String • truncate active_support/core_ext/string/ filters.rb "Oh dear! Oh dear! I shall be late!".truncate(20) # => "Oh dear! Oh dear!..." "Oh dear! Oh dear! I shall be late!".truncate(20, :omission => '&hellip;') # => "Oh dear! Oh &hellip;" … "Oh dear! Oh dear! I shall be late!".truncate(18) # => "Oh dear! Oh dea..." "Oh dear! Oh dear! I shall be late!".truncate(18, :separator => ' ') # => "Oh dear! Oh..."
  • 10. Ext. to String • Output safety - inquiry active_support/core_ext/string/ inquiry.rb "production".inquiry.production? # => true "active".inquiry.inactive?       # => false a StringInquirer object
  • 11. Ext. to String • Output safety - Key-based interpolation active_support/core_ext/string/ interpolation.rb "Total is %<total>.02f" % {:total => 43.1}  # => Total is 43.10 "I say %{foo}" % {:foo => "wadus"}          # => "I say wadus" "I say %{woo}" % {:foo => "wadus"}          # => KeyError
  • 12. Ext. to String • Output safety - start_with? / ends_with? active_support/core_ext/string/ starts_ends_with.rb "foo".starts_with?("f") # => true "foo".ends_with?("o")   # => true
  • 13. Ext. to String • Output safety - strip_heredoc active_support/core_ext/string/ strip.rb if options[:usage]   puts <<-USAGE.strip_heredoc     This command does such and such.       Supported options are:       -h         This message       ...   USAGE end
  • 14. Ext. to String • Access - at(position) active_support/core_ext/string/ access.rb "hello".at(0)  # => "h" "hello".at(4)  # => "o" "hello".at(-1) # => "o" "hello".at(10) # => ERROR if < 1.9, nil in 1.9
  • 15. Ext. to String • Access - from(position) active_support/core_ext/string/ access.rb "hello".from(0)  # => "hello" "hello".from(2)  # => "llo" "hello".from(-2) # => "lo" "hello".from(10) # => "" if < 1.9, nil in 1.9
  • 16. Ext. to String • Access - to(position) active_support/core_ext/string/ access.rb "hello".to(0)  # => "h" "hello".to(2)  # => "hel" "hello".to(-2) # => "hell" "hello".to(10) # => "hello"
  • 17. Ext. to String • Access - first/last active_support/core_ext/string/ access.rb str.first(n) or str.to(n-1) str.last(n) or str.from(-n)
  • 18. Ext. to String • Inflections active_support/core_ext/string/ inflections.rb • pluralize • singularize • camerlize • underscore • titleize • dasherize • demodulize • deconstantize • parameterize • tableize • classify • constantize • humanize • foreign_key
  • 20.