The document discusses various ways to improve Ruby and ActiveRecord syntax through custom methods and techniques like method missing. It provides examples of mapping database queries to method calls for cleaner code, handling multi-database connections, and generating classes on demand through constant missing. The overall goal is to explore how Ruby syntax and patterns can be enhanced for more readable and intuitive code.
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupKacper Gunia
Slides from my talk at Symfony UK Meetup. London, 20 Aug 2014. http://twitter.com/cakper
Video: https://www.youtube.com/watch?v=cha92Og9M5A
More Domain-Driven Design related content at: https://domaincentric.net/
How to Design a Great API (using flask) [ploneconf2017]Devon Bernard
How do you build an API that developers love building and consumers love using?
There's a lot that goes into creating a great API. This presentation shares some tips & tricks, architectural patterns, and best practices that go into building a great engineering environment around your API.
Talk presented on Oct 18, 2017 at PloneConf2017.
Topics covered by this talk:
Intuitive Practices:
standardization, configuration/environment files, ORMs, SQLAlchemy, database migrations, Alembic, database seeds, requirements.txt, package management, dependency management, setup scripts
Durable Practices:
Unit Tests, virtual environments, flush vs commit, error rollbacks, request lifecycle, session lifecycle
Flexible Practices:
Directory structures, application factories, blueprints, python debugger
Reliable Practices:
Logging, progressive rollouts, slack hooks, cron health checks, api versioning, api analytics
Use Friendly Practices:
Endpoint design, endpoint documentation, debugging tools, postman
Speed Practices:
Python profiling, Bulk SQL Inserts, caching
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupKacper Gunia
Slides from my talk at Symfony UK Meetup. London, 20 Aug 2014. http://twitter.com/cakper
Video: https://www.youtube.com/watch?v=cha92Og9M5A
More Domain-Driven Design related content at: https://domaincentric.net/
How to Design a Great API (using flask) [ploneconf2017]Devon Bernard
How do you build an API that developers love building and consumers love using?
There's a lot that goes into creating a great API. This presentation shares some tips & tricks, architectural patterns, and best practices that go into building a great engineering environment around your API.
Talk presented on Oct 18, 2017 at PloneConf2017.
Topics covered by this talk:
Intuitive Practices:
standardization, configuration/environment files, ORMs, SQLAlchemy, database migrations, Alembic, database seeds, requirements.txt, package management, dependency management, setup scripts
Durable Practices:
Unit Tests, virtual environments, flush vs commit, error rollbacks, request lifecycle, session lifecycle
Flexible Practices:
Directory structures, application factories, blueprints, python debugger
Reliable Practices:
Logging, progressive rollouts, slack hooks, cron health checks, api versioning, api analytics
Use Friendly Practices:
Endpoint design, endpoint documentation, debugging tools, postman
Speed Practices:
Python profiling, Bulk SQL Inserts, caching
And now you have two problems. Ruby regular expressions for fun and profit by...Codemotion
A wise hacker said: Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
Regular expressions are a powerful tool in our hands and a first class citizen in ruby so it is tempting to overuse them. But knowing them and using them properly is a fundamental asset of every developer.
We’ll see hands-on examples of proper Reg Exps usage in ruby code, we’ll also look at bad and ugly cases and learn how to approach writing, testing and debugging regular expressions.
A presentation with tips and tools on how to integrate batch and asynchronous operations in a generic ruby on rails application.
Did this at rubyday.it 2011
Lean React - Patterns for High Performance [ploneconf2017]Devon Bernard
Modern web tools are enabling developers to build web apps in no-wifi and low-fi environments. This talk is about performance and how frontend engineers can create a better user experience while using less resources.
Talk presented on Oct 20, 2017 at PloneConf2017.
Topics:
Airplane mode for web apps:
Mobile and native apps get lots of praise for offline mode. But why aren’t we seeing more web-apps using this. Two reasons: persistent data and code storage. We can now provide offline apps with Web Workers and IndexedDB that also improve the smoothness and robustness of our web apps in high bandwidth environments.
Redux:
Persisting state, store middleware, store subscriptions, normalizing data, normalizr, pure reducers, redux dev tools
Components:
Data heavy pages, component blocks, component skeletons, component lifecycle, shouldComponentUpdate, virtual dom, chrome render tools, method binding
Actions:
ActionTypes, action chaining, promises, store.getState()
General:
env files, route wrappers, offline first, web workers, indexeddb, eslint, airbnb style guide
We start with why you should use task queues. Then we show a few straightforward examples with Python and Celery and Ruby and Resque.
Finally, we wrap up with a quick example of a task queue in PHP using Redis.
https://github.com/bryanhelmig/phqueue
Ten useful JavaScript tips & best practicesAnkit Rastogi
In this presentation there are ten useful JavaScript techniques which can be included in your application easily with less friction along with some AngularJs tips and best practices as a bonus. These tips and best practices are accompanied by examples & will cover script loading, design pattern, performance optimization and other areas.
Since best practices are very subjective topics, proper benchmarking needs to be done.
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
The founder of ctrleff demonstrates his methodology of web development that has evolved through the years to find the perfect balance between speed and scalability.
Video presentation: https://www.youtube.com/watch?v=jLAFXQ1Av50
Most applications written in Ruby are great, but also exists evil code applying WOP techniques. There are many workarounds in several programming languages, but in Ruby, when it happens, the proportion is bigger. It's very easy to write Ruby code with collateral damage.
You will see a collection of bad Ruby codes, with a description of how these codes affected negatively their applications and the solutions to fix and avoid them. Long classes, coupling, misapplication of OO, illegible code, tangled flows, naming issues and other things you can ever imagine are examples what you'll get.
With more and more sites falling victim to data theft, you've probably read the list of things (not) to do to write secure code. But what else should you do to make sure your code and the rest of your web stack is secure ? In this tutorial we'll go through the basic and more advanced techniques of securing your web and database servers, securing your backend PHP code and your frontend javascript code. We'll also look at how you can build code that detects and blocks intrusion attempts and a bunch of other tips and tricks to make sure your customer data stays secure.
And now you have two problems. Ruby regular expressions for fun and profit by...Codemotion
A wise hacker said: Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
Regular expressions are a powerful tool in our hands and a first class citizen in ruby so it is tempting to overuse them. But knowing them and using them properly is a fundamental asset of every developer.
We’ll see hands-on examples of proper Reg Exps usage in ruby code, we’ll also look at bad and ugly cases and learn how to approach writing, testing and debugging regular expressions.
A presentation with tips and tools on how to integrate batch and asynchronous operations in a generic ruby on rails application.
Did this at rubyday.it 2011
Lean React - Patterns for High Performance [ploneconf2017]Devon Bernard
Modern web tools are enabling developers to build web apps in no-wifi and low-fi environments. This talk is about performance and how frontend engineers can create a better user experience while using less resources.
Talk presented on Oct 20, 2017 at PloneConf2017.
Topics:
Airplane mode for web apps:
Mobile and native apps get lots of praise for offline mode. But why aren’t we seeing more web-apps using this. Two reasons: persistent data and code storage. We can now provide offline apps with Web Workers and IndexedDB that also improve the smoothness and robustness of our web apps in high bandwidth environments.
Redux:
Persisting state, store middleware, store subscriptions, normalizing data, normalizr, pure reducers, redux dev tools
Components:
Data heavy pages, component blocks, component skeletons, component lifecycle, shouldComponentUpdate, virtual dom, chrome render tools, method binding
Actions:
ActionTypes, action chaining, promises, store.getState()
General:
env files, route wrappers, offline first, web workers, indexeddb, eslint, airbnb style guide
We start with why you should use task queues. Then we show a few straightforward examples with Python and Celery and Ruby and Resque.
Finally, we wrap up with a quick example of a task queue in PHP using Redis.
https://github.com/bryanhelmig/phqueue
Ten useful JavaScript tips & best practicesAnkit Rastogi
In this presentation there are ten useful JavaScript techniques which can be included in your application easily with less friction along with some AngularJs tips and best practices as a bonus. These tips and best practices are accompanied by examples & will cover script loading, design pattern, performance optimization and other areas.
Since best practices are very subjective topics, proper benchmarking needs to be done.
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
The founder of ctrleff demonstrates his methodology of web development that has evolved through the years to find the perfect balance between speed and scalability.
Video presentation: https://www.youtube.com/watch?v=jLAFXQ1Av50
Most applications written in Ruby are great, but also exists evil code applying WOP techniques. There are many workarounds in several programming languages, but in Ruby, when it happens, the proportion is bigger. It's very easy to write Ruby code with collateral damage.
You will see a collection of bad Ruby codes, with a description of how these codes affected negatively their applications and the solutions to fix and avoid them. Long classes, coupling, misapplication of OO, illegible code, tangled flows, naming issues and other things you can ever imagine are examples what you'll get.
With more and more sites falling victim to data theft, you've probably read the list of things (not) to do to write secure code. But what else should you do to make sure your code and the rest of your web stack is secure ? In this tutorial we'll go through the basic and more advanced techniques of securing your web and database servers, securing your backend PHP code and your frontend javascript code. We'll also look at how you can build code that detects and blocks intrusion attempts and a bunch of other tips and tricks to make sure your customer data stays secure.
I will be a developer for another 37 years; and by that time I might have created or maintained
500 to 1000 open source projects. In the last 3 years it is already a become maintenance challenge
and in another 37 years I may be begging to retire. That is, unless we can solve the problem today:
how to go from 1 to 1000 open source projects and still enjoy yourself.
This talk will challenge much of the dogma of open source and will make you rethink what is open source? And how the hell do you live with it once its written?
One of the great things about Ruby and Rails is the "Ruby Community". Where is it? If you are new to Ruby, how do you find it? Once you do find it - your local Ruby club - what do you find there? Let's explore how we can run Ruby clubs and how to create new clubs.
As WordPress and Genesis Developers, the code is our craft, our art. Adopting proven software development principles and keys to quality code into our workflow elevates our art form. In this session, we explore the why, when, and how of writing quality code by design.
fog or: How I Learned to Stop Worrying and Love the CloudWesley Beary
Learn how to easily get started on cloud computing with fog. If you can control your infrastructure choices, you’ll make better choices in development and get what you need in production. You'll get an overview of fog and concrete examples to give you a head start on your provisioning workflow.
Where's My SQL? Designing Databases with ActiveRecord MigrationsEleanor McHugh
A presentation given at RoReXchange in February 2007. Covers some abuses of the ActiveRecord Migrations mechanism along with examples of simple Rails plug-in design.
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)Wesley Beary
Cloud computing scared the crap out of me - the quirks and nightmares of provisioning cloud computing, dns, storage, ... on AWS, Terremark, Rackspace, ... - I mean, where do you even start?
Since I couldn't find a good answer, I undertook the (probably insane) task of creating one. fog gives you a place to start by creating abstractions that work across many different providers, greatly reducing the barrier to entry (and the cost of switching later). The abstractions are built on top of solid wrappers for each api. So if the high level stuff doesn't cut it you can dig in and get the job done. On top of that, mocks are available to simulate what clouds will do for development and testing (saving you time and money).
You'll get a whirlwind tour of basic through advanced as we create the building blocks of a highly distributed (multi-cloud) system with some simple Ruby scripts that work nearly verbatim from provider to provider. Get your feet wet working with cloud resources or just make it easier on yourself as your usage gets more complex, either way fog makes it easy to get what you need from the cloud.
The OpenStack Edition adds my concerns about OpenStack API development, including things that have already been fixed and things that we haven't yet encountered. Hopefully this consumer perspective can help shed light on some rough spots.
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challengesHolger Mueller
Holger Mueller of Constellation Research shares his key takeaways from SAP's Sapphire confernece, held in Orlando, June 3rd till 5th 2024, in the Orange Convention Center.
Implicitly or explicitly all competing businesses employ a strategy to select a mix
of marketing resources. Formulating such competitive strategies fundamentally
involves recognizing relationships between elements of the marketing mix (e.g.,
price and product quality), as well as assessing competitive and market conditions
(i.e., industry structure in the language of economics).
An introduction to the cryptocurrency investment platform Binance Savings.Any kyc Account
Learn how to use Binance Savings to expand your bitcoin holdings. Discover how to maximize your earnings on one of the most reliable cryptocurrency exchange platforms, as well as how to earn interest on your cryptocurrency holdings and the various savings choices available.
B2B payments are rapidly changing. Find out the 5 key questions you need to be asking yourself to be sure you are mastering B2B payments today. Learn more at www.BlueSnap.com.
Navigating the world of forex trading can be challenging, especially for beginners. To help you make an informed decision, we have comprehensively compared the best forex brokers in India for 2024. This article, reviewed by Top Forex Brokers Review, will cover featured award winners, the best forex brokers, featured offers, the best copy trading platforms, the best forex brokers for beginners, the best MetaTrader brokers, and recently updated reviews. We will focus on FP Markets, Black Bull, EightCap, IC Markets, and Octa.
Discover the innovative and creative projects that highlight my journey throu...dylandmeas
Discover the innovative and creative projects that highlight my journey through Full Sail University. Below, you’ll find a collection of my work showcasing my skills and expertise in digital marketing, event planning, and media production.
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.AnnySerafinaLove
This letter, written by Kellen Harkins, Course Director at Full Sail University, commends Anny Love's exemplary performance in the Video Sharing Platforms class. It highlights her dedication, willingness to challenge herself, and exceptional skills in production, editing, and marketing across various video platforms like YouTube, TikTok, and Instagram.
Company Valuation webinar series - Tuesday, 4 June 2024FelixPerez547899
This session provided an update as to the latest valuation data in the UK and then delved into a discussion on the upcoming election and the impacts on valuation. We finished, as always with a Q&A
At Techbox Square, in Singapore, we're not just creative web designers and developers, we're the driving force behind your brand identity. Contact us today.
4. $ sudo gem install charesc
$ irb
>> $KCODE = quot;uquot;
>> require 'rubygems'
>> require 'charesc'
>> quot;charesc is made by Martin D#{U00FC}rstquot;
=> quot;charesc is made by Martin Dürstquot;
>> U00FC
=> quot;üquot;
>> quot;303274quot;
=> quot;üquot;
charesc
5. Active
Records
SELECT * FROM conferences WHERE (start_date > '2007-06-07')
# But, much nicer is...
6. Active
Records
SELECT * FROM conferences WHERE (start_date > '2007-06-07')
# But, much nicer is...
Conference.find(:all,
:conditions => [‘start_date > ?’,Date.today])
7. Active Records
SELECT conferences.quot;idquot; AS t0_r0,
conferences.quot;namequot; AS t0_r2, ...,
conference_sessions.quot;idquot; AS t1_r0,
conference_sessions.quot;conference_idquot; AS t1_r1, ...
FROM conferences
LEFT OUTER JOIN conference_sessions
ON conference_sessions.conference_id = conferences.id
WHERE (start_date < '2007-05-26')
# But, definitely easier and nicer is...
8. Active Records
SELECT conferences.quot;idquot; AS t0_r0,
conferences.quot;namequot; AS t0_r2, ...,
conference_sessions.quot;idquot; AS t1_r0,
conference_sessions.quot;conference_idquot; AS t1_r1, ...
FROM conferences
LEFT OUTER JOIN conference_sessions
ON conference_sessions.conference_id = conferences.id
WHERE (start_date < '2007-05-26')
# But, definitely easier and nicer is...
Conference.find(:all,
:conditions => ['start_date < ?', Date.today],
:include => :conference_sessions)
9. Sexy
Syntax
ActiveRecords
- no SQL
... + marshalling
to objects
11. Schemas
create_table :conferences do |t|
t.fkey :user
t.string :name, :limit => 50
t.text :description
t.date :start_date, :end_date
t.auto_dates
end
# instead of...
I can never
remember
SQL syntax
12. Schemas
create_table :conferences do |t|
t.fkey :user
t.string :name, :limit => 50
t.text :description
t.date :start_date, :end_date
t.auto_dates
end
# instead of...
Look up SQL on
I can never
remember
SQL syntax
13. Composite
Primary Keys
ProductHistory.find(:first, :conditions =>
['id = ? and start_date = ?', 56, Date.new(2000,5,5)])
# rather...
What about
Ruby syntax
improving on
other Ruby
syntax?
14. Composite
Primary Keys
ProductHistory.find(:first, :conditions =>
['id = ? and start_date = ?', 56, Date.new(2000,5,5)])
# rather...
ProductHistory.find(56, Date.new(2000,5,5))
What about
Ruby syntax
class ProductHistory < ActiveRecord::Base improving on
other Ruby
set_primary_keys :id, :start_date syntax?
end
15. What’s this do? #1
Nice syntax
can quickly tell
you want the
code will does
@user.conference_sessions_for(@conference)
16. What’s this do? #1
Nice syntax
can quickly tell
you want the
code will does
@user.conference_sessions_for(@conference)
# Returns all ConferenceSessions
# for a user at a conference
17. What’s this do? #2
@conference_attendees.map_id_and_login_and_full_name
20. What’s this do? #3
@to_user = @target_db::User.find(params[:id])
User.find(params[:id])
21. What’s this do? #3
@to_user = @target_db::User.find(params[:id])
User.find(params[:id])
@to_user.update(@from_db::User.find(params[:id]))
22. What’s this do? #3
@to_user = @target_db::User.find(params[:id])
User.find(params[:id])
@to_user.update(@from_db::User.find(params[:id]))
# Copies a User from one database to another
# see Magic Multi-Connection
# http://magicmodels.rubyforge.org
24. What’s this do? #1
Nice syntax
can quickly tell
you want the
code will does
@user.conference_sessions_for(@conference)
25. What’s this do? #1
Nice syntax
can quickly tell
you want the
code will does
@user.conference_sessions_for(@conference)
# Returns all ConferenceSessions
# for a user at a conference
26. What’s this do? #1
class User < ActiveRecord::Base
has_many :conference_sessions
def conference_sessions_for(conference)
conference_sessions.find(:all,
:conditions => ['conference_id = ?', conference])
end
end
No meta-magic, but it gives nice syntax
30. Cute ways to use #map
@users = User.find(:all)
@users.map {|user| user.login}
# => ['drnic', 'topfunky', 'dhh']
@users.map &:login
# => ['drnic', 'topfunky', 'dhh']
# but it gets ugly when you chain them...
@users.map(&:login).map(&:size)
# => [5, 8, 3]
31. Cute ways to use #map
# So, instead of...
@users.map(&:login).map(&:size)
# We might like...
@users.map_login.map_size
32. Remember find_by_xxx ?
def method_missing(method_id, *arguments)
pattern = /^find_(all_by|by)_([_a-zA-Z]w*)$/
if match = pattern.match(method_id.to_s)
finder = determine_finder(match)
# from active_record/base.rb, line 1190
33. Dissecting the request
def method_missing(method, *args, &block)
pattern = /(map|select|...)_by_([w_]+??)/
if (match = method.match(pattern))
iterator, callmethod = match[1], match[2]
# changed ‘find’ to ‘map’
# or select, reject, each, collect...
34. Iterating the request
# continued...
iterator, callmethod = match[1], match[2]
self.send(iterator) {|obj| obj.send callmethod }
# @array.map_by_foo
# callmethod => ‘foo’
# #foo invoked on each element of Array
35. Iterating many callmethods
# continued...
iterator, callmethod = match[1], match[2]
callmethods = callmethod.split('_and_')
callmethods.map do |callmethod|
self.send(iterator) {|obj| obj.send callmethod }
end
# @array.map_by_foo_and_bar
# callmethods => [‘foo’, ‘bar’]
# #foo and #bar invoked on each element of Array
37. map_by_method gem
# for complete source:
$ gem install map_by_method
$ mate $RUBYGEMS_PATH/map_by_method-0.6.0/lib/map_by_method.rb
# add the following to your ~/.irbrc
require 'map_by_method'
39. What’s this do? #3
@to_user = @target_db::User.find(params[:id])
User.find(params[:id])
40. What’s this do? #3
@to_user = @target_db::User.find(params[:id])
User.find(params[:id])
@to_user.update(@from_db::User.find(params[:id]))
41. What’s this do? #3
@to_user = @target_db::User.find(params[:id])
User.find(params[:id])
@to_user.update(@from_db::User.find(params[:id]))
# Copies a User from one database to another
# see Magic Multi-Connection
# http://magicmodels.rubyforge.org
43. MMC - alternate ideas
@db::User.find(params[:id])
# but I would have preferred...
User.find(params[:id]).from_db(@db)
44. MMC - alternate ideas
@db::User.find(params[:id])
# but I would have preferred...
User.find(params[:id]).from_db(@db)
# but we’d need FindProxies
# like AssociationProxies
46. class creator helper
class Module
def create_class(class_name, superclass = Object, &block)
klass = Class.new superclass, &block
self.const_set class_name, klass
end
end
>> module Connection; end
>> Connection.create_class 'User'
=> Connection::User
47. class creator helper
class Module
def create_class(class_name, superclass = Object, &block)
klass = Class.new superclass, &block
self.const_set class_name, klass
end
end
>> module Connection; end
>> Connection.create_class 'User'
=> Connection::User
@db::User
49. const_missing
class Module
alias :old_const_missing :const_missing
def const_missing(const_id)
return old_const_missing(const_id) rescue nil
target_class = quot;::#{const_id}quot;.constantize rescue nil
raise NameError.new(quot;bad constant #{const_id}quot;) unless target_class
create_class(const_id, target_class)
end
end
50. const_missing
class Module
alias :old_const_missing :const_missing
def const_missing(const_id)
return old_const_missing(const_id) rescue nil
target_class = quot;::#{const_id}quot;.constantize rescue nil
raise NameError.new(quot;bad constant #{const_id}quot;) unless target_class
create_class(const_id, target_class)
end
end
magic multi-connections
51. Picks up root classes
class Person; end
module Remote
establish_connection :other
end
>> Remote::Person.superclass
=> Person
52. const_missing
class Module
def const_missing(const_id)
return old_const_missing(class_id) rescue nil
table_name = DrNicMagicModels::Schema.models[const_id]
raise NameError.new(quot;bad constant #{const_id}quot;) unless table_name
create_class(class_id, ActiveRecord::Base) do
set_table_name table_name
end
end
end
“Does the class name match to a table name?”
53. const_missing
class Module
def const_missing(const_id)
return old_const_missing(class_id) rescue nil
table_name = DrNicMagicModels::Schema.models[const_id]
raise NameError.new(quot;bad constant #{const_id}quot;) unless table_name
create_class(class_id, ActiveRecord::Base) do
set_table_name table_name
end
end
dr nic’s magic models
end
“Does the class name match to a table name?”