The document appears to be notes from a presentation on Ruby on Rails. It discusses various features and updates to Rails over time, including the introduction of Active Record, Action Pack, Action View and other core components in early versions of Rails. Later sections cover additions like Ajax functionality, exceptions handling, authentication, RESTful routing and more. Various dates are mentioned corresponding to different Rails releases.
Backbone.js helps structure you javascript application code in a scalable way.
In this keynote I demonstrate how to use it in a simple walk-through example, and discuss the advantages of using an MVC framework.
Fórum de Software Livre do Serpro RJ 2009Fabio Akita
Esta palestra é muito parecida com a que eu também ministrei no evento Dev in Rio 2009, portanto os slides são quase iguais caso você já tenha baixado.
A apresentação fala sobre filosofias, valores e idéias ágeis e como elas são a fundação da comunidade Ruby on Rails e do ecossistema que se formou ao seu redor.
Alguns dos vídeos mostrados estão disponíveis em http://vimeo.com/akitaonrails.com
I’ve been using, teaching, and evangelizing about jQuery for years. The library's simplicity is seductive; after a while, it kind of writes itself. So why did I venture into the unknown world of Dojo for a recent project? Find out what I learned about JavaScript code organization, inheritance, dependency management, and more in a whirlwind beginner's tour of a toolkit that answers some of the big questions surrounding JavaScript development.
Backbone.js helps structure you javascript application code in a scalable way.
In this keynote I demonstrate how to use it in a simple walk-through example, and discuss the advantages of using an MVC framework.
Fórum de Software Livre do Serpro RJ 2009Fabio Akita
Esta palestra é muito parecida com a que eu também ministrei no evento Dev in Rio 2009, portanto os slides são quase iguais caso você já tenha baixado.
A apresentação fala sobre filosofias, valores e idéias ágeis e como elas são a fundação da comunidade Ruby on Rails e do ecossistema que se formou ao seu redor.
Alguns dos vídeos mostrados estão disponíveis em http://vimeo.com/akitaonrails.com
I’ve been using, teaching, and evangelizing about jQuery for years. The library's simplicity is seductive; after a while, it kind of writes itself. So why did I venture into the unknown world of Dojo for a recent project? Find out what I learned about JavaScript code organization, inheritance, dependency management, and more in a whirlwind beginner's tour of a toolkit that answers some of the big questions surrounding JavaScript development.
When you move beyond adding simple enhancements to your website with jQuery and start building full-blown client-side applications, how do you organize your code? At this month's Triangle JS Meetup, we'll take a look at patterns for application development using jQuery that promote the principles of tight encapsulation and loose coupling, including classes, the publish/subscribe paradigm, and dependency management and build systems.
Minha palestra sobre Ruby on Rails, Cultura e Ecossistema na Dev in Rio 2009. Vejam alguns dos meus vídeos dessa palestra em http://vimeo.com/akitaonrails
I gave this presentation at the 2010 Scotch on the Rocks conference. It features a brief explanation of why HTML5 and CSS3 are necessary, and then goes on to cover most of the cool new features of HTML5 and CSS3 that are supported across most browsers at the time of publication., including <video>, <canvas>, HTML5 forms, the new HTML5 elements, box-shadow, text-shadow, web fonts, media queries, and more. Companion code examples are available at http://people.opera.com/cmills/HTML5_CSS3_examples.zip
jQuery is a JavaScript library which allows you to develop solutions with less code, in less time. You can build interactive prototypes for your prospective clients, or take an existing solution and add new dynamic behaviour with little effort.
We will see how jQuery can be used to quickly and concisely apply JavaScript behaviour to your web app. It will cover selectors, Ajax, DOM manipulation and more. The aim: to produce lean unobtrusive JavaScript with jQuery.
This was from a talk I gave at New York Front End Coders in July 2013 on how to create random CSS Animations.
CSS Keyframe Animations are definitions in CSS that outline the CSS properties to be animated and the points in time during the life of the animation that these animations should be achieved. This can lead to huge amounts of CSS when trying to make something appear random.
This talk sought to explain how randomisation (of a sort) was achieved. Hopefully the slides themselves can communicate this.
Things you should know about jQuery JavaScript library. A JavaScript library designed to hide painful cross-browser compatibility issues while presenting a solid, usable, API.
This presentation covers some jQuery basics, as well as some general concepts you should understand about jQuery. You will find other tips and tricks sprinkled throughout before the live coding session starts.
The code from the live coding session is available here: https://github.com/dcneiner/jQuery-Bling and covers far more advanced topics than the slide portion of this presentation.
When you move beyond adding simple enhancements to your website with jQuery and start building full-blown client-side applications, how do you organize your code? At this month's Triangle JS Meetup, we'll take a look at patterns for application development using jQuery that promote the principles of tight encapsulation and loose coupling, including classes, the publish/subscribe paradigm, and dependency management and build systems.
Minha palestra sobre Ruby on Rails, Cultura e Ecossistema na Dev in Rio 2009. Vejam alguns dos meus vídeos dessa palestra em http://vimeo.com/akitaonrails
I gave this presentation at the 2010 Scotch on the Rocks conference. It features a brief explanation of why HTML5 and CSS3 are necessary, and then goes on to cover most of the cool new features of HTML5 and CSS3 that are supported across most browsers at the time of publication., including <video>, <canvas>, HTML5 forms, the new HTML5 elements, box-shadow, text-shadow, web fonts, media queries, and more. Companion code examples are available at http://people.opera.com/cmills/HTML5_CSS3_examples.zip
jQuery is a JavaScript library which allows you to develop solutions with less code, in less time. You can build interactive prototypes for your prospective clients, or take an existing solution and add new dynamic behaviour with little effort.
We will see how jQuery can be used to quickly and concisely apply JavaScript behaviour to your web app. It will cover selectors, Ajax, DOM manipulation and more. The aim: to produce lean unobtrusive JavaScript with jQuery.
This was from a talk I gave at New York Front End Coders in July 2013 on how to create random CSS Animations.
CSS Keyframe Animations are definitions in CSS that outline the CSS properties to be animated and the points in time during the life of the animation that these animations should be achieved. This can lead to huge amounts of CSS when trying to make something appear random.
This talk sought to explain how randomisation (of a sort) was achieved. Hopefully the slides themselves can communicate this.
Things you should know about jQuery JavaScript library. A JavaScript library designed to hide painful cross-browser compatibility issues while presenting a solid, usable, API.
This presentation covers some jQuery basics, as well as some general concepts you should understand about jQuery. You will find other tips and tricks sprinkled throughout before the live coding session starts.
The code from the live coding session is available here: https://github.com/dcneiner/jQuery-Bling and covers far more advanced topics than the slide portion of this presentation.
The GPars (Groovy Parallel Systems) project provides multiple abstractions for concurrent, parallel programming in Groovy and Java. Rather than dealing directly with threads, synchronization, and locks, or even the java.util.concurrent classes added in Java 5, the project allows you to think in terms of actors, data flows, or composable asynchronous functions (to name a few).
In this talk, I covered the basics of GPars, including what it's like to learn to use it. Although I've done a fair amount of concurrent programming, I've just started using GPars. As such, this talk should be suitable for Groovy beginners.
Background processing is an important tool in web development. Some
things just can't optimized enough for the normal request/response cycle
of a web site and need to be run asynchronously. Ruby on Rails doesn't provide
you with any real out of the box solution. There are a lot of external
options available and this part of Rails is lacking any real convention
or standard.
In this presentation, we will talk about how to choose and implement a
solution that fits your needs. We will start with some basic options
using built in Rails tools and we will cover some of the more popular
solutions solutions out there such as BackgrounDRb, Background Job,
Delayed Job, Workling and more.
Rob Mack has been working with Rails professionally on and off since
2005. Rob currently works for VitalSource Technologies.
Tek 2013 - Building Web Apps from a New Angle with AngularJSPablo Godel
AngularJS is a new JavaScript framework, backed by Google, for building powerful, complex and rich client-side web applications. We will go over the features and basics of building a web application with AngularJS and we will demonstrate how to communicate with a REST server built with PHP.
Open Source Monitoring for Java with JMX and Graphite (GeeCON 2013)Cyrille Le Clerc
Fast feedback from monitoring is a key of Continuous Delivery. JMX is the right Java API to do so but it unfortunately stayed underused and underappreciated as it was difficult to connect to monitoring and graphing systems.
Throw in the sin bin the poor solutions based on log files and weakly secured web interfaces! A new generation of Open Source tooling makes it easy to graph java application metrics and integrate them to traditional monitoring systems like Nagios.
Following the logic of DevOps, we will look together how best to integrate the monitoring dimension in a project: from design to development, to QA and finally to production on both traditional deployment and in the Cloud.
Come and discover how the JmxTrans-Graphite ticket can make your life easier.
From the "Rails: Hot or Not?" session at Sioux (Eindhoven, NL, May 23, 2007). An introduction to Rails and programming for the web, targeted at embedded developers. What are the challenges of web development? What technologies do we have at our disposal, and how does Ruby on Rails attack the problem?
Desmistificando Mitos de Tech Startups - Intercon 2017Fabio Akita
Versão apresentada no evento Intercon 2017. Desmistificando 10 dos principais mitos ainda repetidos pela comunidade de empreendedorismo e tech startups.
30 Days to Elixir and Crystal and Back to RubyFabio Akita
Presented at Ruby Dev Summit, a journey through learning Elixir, Crystal and making Ruby better in the process, and why Ruby still can compete in the Web.
Focada em jovens estudantes ou recém-formados para terem uma perspectiva sobre o que almejar na carreira de TI. Versão apresentada pela primeira vez no 6o meetup do Cricíuma Dev.
This is the opening keynote for the 1st edition of THE CONF (www.theconf.club). It has full presenter notes. The video recording will be available at InfoQ Brasil.
Desmistificando Mitos de Startups - Sebrae - APFabio Akita
O mundo de startups se tornou um grande show. A maioria não entende que a sorte tem um papel mais forte do que se imagina. E sem conhecimento, experiência e paciência, Não existe caminho simples para o sucesso.
A Journey through New Languages - Locaweb Tech DayFabio Akita
An exercise started in 2014 going all the way to early 2016 of a simple crawler made in (ugly) Ruby first, then moving to Elixir, to Crystal and back to Ruby and what we can take out of it.
A Journey through new Languages - Intercon 2016Fabio Akita
Minha palestra apresentando minha jornada sobre um código Ruby feito com otimização prematura, passando por Elixir, Crystal e de volta ao Ruby, escrito da forma arquiteturalmente mais "correta" e que no final se tornou até mais performática.
Esta é a minha palestra "Premature Optimization" versão "Code-Only". #THECONFBR
The Open Commerce Conference - Premature Optimisation: The Root of All EvilFabio Akita
This is the talk I presented in NYC at the Spree Conference. It's about how we may be making bad decisions out of blindly following misleading pitches. To avoid it, we just need to go back to the basics of CS: Don't optimize prematurely. Here's how.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
20 Comprehensive Checklist of Designing and Developing a WebsitePixlogix Infotech
Dive into the world of Website Designing and Developing with Pixlogix! Looking to create a stunning online presence? Look no further! Our comprehensive checklist covers everything you need to know to craft a website that stands out. From user-friendly design to seamless functionality, we've got you covered. Don't miss out on this invaluable resource! Check out our checklist now at Pixlogix and start your journey towards a captivating online presence today.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Building RAG with self-deployed Milvus vector database and Snowpark Container...Zilliz
This talk will give hands-on advice on building RAG applications with an open-source Milvus database deployed as a docker container. We will also introduce the integration of Milvus with Snowpark Container Services.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
53. # GET /weblog
# GET /weblog.xml
# GET /weblog.rss
class WeblogController < ActionController::Base
def index
@posts = Post.find :all
respond_to do |format|
format.html
format.xml { render :xml => @posts.to_xml }
format.rss { render :action => "feed.rxml" }
end
end
end
Tuesday, December 15, 2009
58. class TrafficLight
include AlterEgo
state :proceed, :default => true do
handle :color { "green" }
transition :to => :caution, :on => :cycle!
end
state :caution do
handle :color { "yellow" }
transition :to => :stop, :on => :cycle!
end
state :stop do
handle :color { "red" }
transition :to => :proceed, :on => :cycle!
end
end
Tuesday, December 15, 2009
59. light = TrafficLight.new
light.color # => "green"
light.cycle!
light.color # => "yellow"
light.cycle!
light.color # => "red"
light.cycle!
light.color # => "green"
• Acts As State Machine (AASM)
• Alter Ego
• State-Fu
http://jmettraux.wordpress.com/2009/07/03/state-machine-workflow-engine/
Tuesday, December 15, 2009
63. # config/initializers/mime_types.rb
Mime.register_alias "text/html", :iphone
# app/controllers/application.rb
class ApplicationController < ActionController::Base
before_filter :adjust_format_for_iphone
private
def adjust_format_for_iphone
if request.env["HTTP_USER_AGENT"] &&
request.env["HTTP_USER_AGENT"][/(iPhone|iPod)/]
request.format = :iphone
end
end
end
Tuesday, December 15, 2009
64. # config/initializers/mime_types.rb
Mime.register_alias "text/html", :iphone
# app/controllers/application.rb
class ApplicationController < ActionController::Base
before_filter :adjust_format_for_iphone
private
def adjust_format_for_iphone
if request.env["HTTP_USER_AGENT"] &&
request.env["HTTP_USER_AGENT"][/(iPhone|iPod)/]
request.format = :iphone
end
end
end
Tuesday, December 15, 2009
65. # config/initializers/mime_types.rb
Mime.register_alias "text/html", :iphone
# app/controllers/application.rb
class ApplicationController < ActionController::Base
before_filter :adjust_format_for_iphone
private
def adjust_format_for_iphone
if request.env["HTTP_USER_AGENT"] &&
request.env["HTTP_USER_AGENT"][/(iPhone|iPod)/]
request.format = :iphone
end
end
end
Tuesday, December 15, 2009
66. # app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
respond_to do |format|
format.html # renders index.html.erb
format.iphone # renders index.iphone.erb
end
end
end
Tuesday, December 15, 2009
67. # app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
respond_to do |format|
format.html # renders index.html.erb
format.iphone # renders index.iphone.erb
end
end
end
Tuesday, December 15, 2009
68. class PostsController < ApplicationController
before_filter :authenticate, :except => [ :index ]
def index
render :text => "Everyone can see me!"
end
def edit
render :text => "I’m not publicly accessible"
end
private
def authenticate
authenticate_or_request_with_http_basic do |user_name,
password|
user_name == "dhh" && password == "secret"
end
end
end
Tuesday, December 15, 2009
69. class PostsController < ApplicationController
before_filter :authenticate, :except => [ :index ]
def index
render :text => "Everyone can see me!"
end
def edit
render :text => "I’m not publicly accessible"
end
private
def authenticate
authenticate_or_request_with_http_basic do |user_name,
password|
user_name == "dhh" && password == "secret"
end
end
end
Tuesday, December 15, 2009
70. class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for
# details
# Uncomment the :secret if you're not using the
# cookie session store
protect_from_forgery # :secret =>
# '9b76dcad7de4d8eca67e9d53329006ac'
end
Tuesday, December 15, 2009
71. class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for
# details
# Uncomment the :secret if you're not using the
# cookie session store
protect_from_forgery # :secret =>
# '9b76dcad7de4d8eca67e9d53329006ac'
end
Tuesday, December 15, 2009
72. class PostsController < ApplicationController
rescue_from User::NotAuthorized, :with => :deny_access
protected
def deny_access
...
end
end
Tuesday, December 15, 2009
73. class PostsController < ApplicationController
rescue_from User::NotAuthorized, :with => :deny_access
protected
def deny_access
...
end
end
Tuesday, December 15, 2009
74. # Your secret key for verifying cookie session data
# integrity. If you change this key, all old sessions
# will become invalid! Make sure the secret is at least
# 30 characters and all random, no regular words or you'll
# be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_my_app_session',
:secret =>
'ec54b1c89c810d5937ede6b2969ee227c7653ffaffb37927a71203ef968
7928d256572ae5c8e66efbf0b9686103b597c3bae537b813fc838580c794
248c428da'
}
Tuesday, December 15, 2009
75. create_table :people do |t|
t.column, "account_id", :integer
t.column, "first_name", :string, :null => false
t.column, "last_name", :string, :null => false
t.column, "description", :text
t.column, "created_at", :datetime
t.column, "updated_at", :datetime
end
create_table :people do |t|
t.integer :account_id
t.string :first_name, :last_name, :null => false
t.text :description
t.timestamps
end
Tuesday, December 15, 2009
76. # sellers.yml
shopify:
name: Shopify
# products.yml
pimp_cup:
seller: shopify
name: Pimp cup
Tuesday, December 15, 2009
95. class ArticlesController < ApplicationController
def show_with_respond_to_block
@article = Article.find(params[:id])
# unless stale? => "304 Not Modified"
if stale?(:last_modified => @article.published_at.utc,
:etag => @article)
respond_to do |wants|
# normal response processing
end
end
end
def show_with_implied_render
@article = Article.find(params[:id])
# If fresh => "304 Not Modified"
fresh_when(:last_modified => @article.published_at.utc,
:etag => @article)
end
end
Tuesday, December 15, 2009
96. class ArticlesController < ApplicationController
def show_with_respond_to_block
@article = Article.find(params[:id])
# unless stale? => "304 Not Modified"
if stale?(:last_modified => @article.published_at.utc,
:etag => @article)
respond_to do |wants|
# normal response processing
end
end
end
def show_with_implied_render
@article = Article.find(params[:id])
# If fresh => "304 Not Modified"
fresh_when(:last_modified => @article.published_at.utc,
:etag => @article)
end
end
Tuesday, December 15, 2009
97. class ArticlesController < ApplicationController
def show_with_respond_to_block
@article = Article.find(params[:id])
# unless stale? => "304 Not Modified"
if stale?(:last_modified => @article.published_at.utc,
:etag => @article)
respond_to do |wants|
# normal response processing
end
end
end
def show_with_implied_render
@article = Article.find(params[:id])
# If fresh => "304 Not Modified"
fresh_when(:last_modified => @article.published_at.utc,
:etag => @article)
end
end
Tuesday, December 15, 2009
98. # config/environments/production.rb:
config.threadsafe!
# config/database.yml
development:
adapter: mysql
username: root
database: myapp_dev
pool: 10
Tuesday, December 15, 2009
99. # config/routes.rb
map.resources :publishers, :shallow => true do |publisher|
publisher.resources :magazines do |magazine|
magazine.resources :photos
end
end
# /publishers/1 ==> publisher_path(1)
# /publishers/1/magazines ==> publisher_magazines_path(1)
# /magazines/2 ==> magazine_path(2)
# /magazines/2/photos ==> magazines_photos_path(2)
# /photos/3 ==> photo_path(3)
Tuesday, December 15, 2009
100. # antes
def full_name
@full_name ||= "#{first_name} #{last_name}"
end
# depois
extend ActiveSupport::Memoizable
def full_name
"#{first_name} #{last_name}"
end
memoize :full_name
Tuesday, December 15, 2009
101. class Vendor < ActiveRecord::Base
has_one :account
delegate :email, :password, :to => :account,
:prefix => true
end
# @vendor.account_email
# @vendor.account_password
class Vendor < ActiveRecord::Base
has_one :account
delegate :email, :password, :to => :account,
:prefix => :owner
end
# @vendor.owner_email
# @vendor.owner_password
Tuesday, December 15, 2009
102. class UserMailer < ActionMailer::Base
def registration(user)
subject "You've registered"
from "system@example.com"
end
end
# layouts/user_mailer.html.erb
class UserMailer < ActionMailer::Base
layout 'email'
...
end
# layouts/email.html.erb
Tuesday, December 15, 2009
109. > rake middleware
use Rack::Lock
use ActionController::Failsafe
use ActionController::Session::CookieStore
use ActionController::ParamsParser
use Rack::MethodOverride
use Rack::Head
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
run ActionController::Dispatcher.new
Tuesday, December 15, 2009
110. # app/metal/poller.rb
class Poller < Rails::Rack::Metal
def call(env)
if env["PATH_INFO"] =~ /^/poller/
[200, {"Content-Type" => "text/html"}, "Hello, World!"]
else
[404, {"Content-Type" => "text/html"}, "Not Found"]
end
end
end
# app/controllers/old_poller_controller.rb
class OldPollerController < ApplicationController
def poller
render :text => "Hello World!"
end
end
Tuesday, December 15, 2009
111. # benchmark the traditional controller
$ ab -n 1000 http://127.0.0.1:3000/old_poller/poller
Requests per second: 408.45 [#/sec] (mean)
Time per request: 2.448 [ms] (mean)
# benchmark the Metal middleware
$ ab -n 1000 http://127.0.0.1:3000/poller
Requests per second: 1154.66 [#/sec] (mean)
Time per request: 0.866 [ms] (mean)
Tuesday, December 15, 2009
114. class Project < ActiveRecord::Base
after_update :save_tasks
validates_associated :tasks
def new_task_attributes=(task_attributes)
task_attributes.each { |attr| tasks.build(attr) }
end
def existing_task_attributes=(task_attributes)
tasks.reject(&:new_record?).each do |task|
attributes = task_attributes[task.id.to_s]
if attributes['_delete'] == '1'
tasks.delete(task)
else
task.attributes = attributes
end
end
end
private
def save_tasks
tasks.each { |task| task.save(false)}
end
end
Tuesday, December 15, 2009
115. class Project < ActiveRecord::Base
has_many :tasks
accept_nested_attributes_for :tasks,
:allow_destroy => true
end
Tuesday, December 15, 2009
118. User.transaction do
User.create(:username => 'Admin')
User.transaction(:requires_new => true) do
User.create(:username => 'Regular')
raise ActiveRecord::Rollback
end
end
User.find(:all) # => Returns only Admin
Tuesday, December 15, 2009
121. class Article < ActiveRecord::Base
default_scope :order => 'created_at DESC'
end
Article.find(:all)
#=> "SELECT * FROM `articles` ORDER BY created_at DESC"
class Article < ActiveRecord::Base
default_scope :order => 'created_at DESC'
named_scope :published, :conditions => { :published => true }
end
Article.published
#=> "SELECT * FROM `articles` WHERE published = true
# ORDER BY created_at DESC"
# Ignore other scoping within this block
Article.with_exclusive_scope { find(:all) }
#=> "SELECT * FROM `articles`
Tuesday, December 15, 2009
122. class Article < ActiveRecord::Base
default_scope :order => 'created_at DESC'
end
Article.find(:all)
#=> "SELECT * FROM `articles` ORDER BY created_at DESC"
class Article < ActiveRecord::Base
default_scope :order => 'created_at DESC'
named_scope :published, :conditions => { :published => true }
end
Article.published
#=> "SELECT * FROM `articles` WHERE published = true
# ORDER BY created_at DESC"
# Ignore other scoping within this block
Article.with_exclusive_scope { find(:all) }
#=> "SELECT * FROM `articles`
Tuesday, December 15, 2009
123. Article.find_each { |a| ... }
# => iterate over all articles, in chunks of 1000 (the default)
Article.find_each(:conditions => { :published => true },
:batch_size => 100 ) { |a| ... }
# iterate over published articles in chunks of 100
Article.find_in_batches do |articles|
articles.each { |a| ... }
end
# => articles is array of size 1000
Article.find_in_batches(batch_size => 100 ) do |articles|
articles.each { |a| ... }
end
# iterate over all articles in chunks of 100
Article.published.find_in_batches(:batch_size => 100 ) do |articles|
...
end
# iterate over published articles in chunks of 100
Tuesday, December 15, 2009
124. Article.find_each { |a| ... }
# => iterate over all articles, in chunks of 1000 (the default)
Article.find_each(:conditions => { :published => true },
:batch_size => 100 ) { |a| ... }
# iterate over published articles in chunks of 100
Article.find_in_batches do |articles|
articles.each { |a| ... }
end
# => articles is array of size 1000
Article.find_in_batches(batch_size => 100 ) do |articles|
articles.each { |a| ... }
end
# iterate over all articles in chunks of 100
Article.published.find_in_batches(:batch_size => 100 ) do |articles|
...
end
# iterate over published articles in chunks of 100
Tuesday, December 15, 2009
125. Article.find_each { |a| ... }
# => iterate over all articles, in chunks of 1000 (the default)
Article.find_each(:conditions => { :published => true },
:batch_size => 100 ) { |a| ... }
# iterate over published articles in chunks of 100
Article.find_in_batches do |articles|
articles.each { |a| ... }
end
# => articles is array of size 1000
Article.find_in_batches(batch_size => 100 ) do |articles|
articles.each { |a| ... }
end
# iterate over all articles in chunks of 100
Article.published.find_in_batches(:batch_size => 100 ) do |articles|
...
end
# iterate over published articles in chunks of 100
Tuesday, December 15, 2009
126. class ArticlesController < ApplicationController
before_filter :digest_authenticate
def digest_authenticate
s = authenticate_or_request_with_http_digest("Admin") do |username|
(@user = User.find_by_username(username)).try(cleartext_password)
end
# If authentication succeeds, log the user in.
# If not, kick back out a failure
# message as the response body
if s
session[:user_id] = @user.id
else
request_http_digest_authentication("Admin",
"Authentication failed")
end
end
end
Tuesday, December 15, 2009
127. class ArticlesController < ApplicationController
before_filter :digest_authenticate
def digest_authenticate
s = authenticate_or_request_with_http_digest("Admin") do |username|
(@user = User.find_by_username(username)).try(cleartext_password)
end
# If authentication succeeds, log the user in.
# If not, kick back out a failure
# message as the response body
if s
session[:user_id] = @user.id
else
request_http_digest_authentication("Admin",
"Authentication failed")
end
end
end
Tuesday, December 15, 2009
128. class ArticlesController < ApplicationController
before_filter :digest_authenticate
def digest_authenticate
s = authenticate_or_request_with_http_digest("Admin") do |username|
(@user = User.find_by_username(username)).try(cleartext_password)
end
# If authentication succeeds, log the user in.
# If not, kick back out a failure
# message as the response body
if s
session[:user_id] = @user.id
else
request_http_digest_authentication("Admin",
"Authentication failed")
end
end
end
Tuesday, December 15, 2009