Slide 1

Slide 1 text

Don’t. @erniemiller Ernie Miller http://erniemiller.org

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

I HAVE DONE A LOT OF STUPID THINGS

Slide 5

Slide 5 text

Real Talk

Slide 6

Slide 6 text

Real Talk

Slide 7

Slide 7 text

Real Talk

Slide 8

Slide 8 text

Real Talk

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

…overestimate how much time you have Don’t...

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

…overestimate how much time you have Don’t...

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

Potential Energy

Slide 26

Slide 26 text

Potential Energy FOR BUSINESS!

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

No content

Slide 32

Slide 32 text

No content

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

…forget your choices have consequences Don’t...

Slide 36

Slide 36 text

Metaprogramming

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

DERP

Slide 41

Slide 41 text

Rules for Class Macros What, not how! Idempotent! Order independent! Straightforward! Free of branching 1 2 3 4 5

Slide 42

Slide 42 text

def self.included(base) base.extend ClassMethods ! base.class_eval do class_attribute :_metasearch_include_attributes, :_metasearch_exclude_attributes class_attribute :_metasearch_include_associations, :_metasearch_exclude_associations class_attribute :_metasearch_methods self._metasearch_include_attributes = self._metasearch_exclude_attributes = self._metasearch_exclude_associations = self._metasearch_include_associations = {} self._metasearch_methods = {} end end

Slide 43

Slide 43 text

def attr_unsearchable(*args) if table_exists? opts = args.extract_options! args.flatten.each do |attr| attr = attr.to_s unless self.columns_hash.has_key?(attr) raise(ArgumentError, "No persisted attribute (column) named #{attr} in #{self}”) end self._metasearch_exclude_attributes = self._metasearch_exclude_attributes.merge( attr => { :if => opts[:if] } ) end end end

Slide 44

Slide 44 text

def attr_searchable(*args) if table_exists? opts = args.extract_options! args.flatten.each do |attr| attr = attr.to_s unless self.columns_hash.has_key?(attr) raise(ArgumentError, "No persisted attribute (column) named #{attr} in #{self}”) end self._metasearch_include_attributes = self._metasearch_include_attributes.merge( attr => { :if => opts[:if] } ) end end end

Slide 45

Slide 45 text

def assoc_unsearchable(*args) opts = args.extract_options! args.flatten.each do |assoc| assoc = assoc.to_s unless self.reflect_on_all_associations.map {|a| a.name.to_s}.include?(assoc) raise(ArgumentError, "No such association #{assoc} in #{self}”) end self._metasearch_exclude_associations = self._metasearch_exclude_associations.merge( assoc => { :if => opts[:if] } ) end end

Slide 46

Slide 46 text

def assoc_searchable(*args) opts = args.extract_options! args.flatten.each do |assoc| assoc = assoc.to_s unless self.reflect_on_all_associations.map {|a| a.name.to_s}.include?(assoc) raise(ArgumentError, "No such association #{assoc} in #{self}”) end self._metasearch_include_associations = self._metasearch_include_associations.merge( assoc => { :if => opts[:if] } ) end end

Slide 47

Slide 47 text

class Article < ActiveRecord::Base attr_searchable :some_public_data, :some_more_searchable_stuff assoc_searchable :search_this_association_why_dontcha end

Slide 48

Slide 48 text

def ransackable_attributes(auth_object = nil) column_names + _ransackers.keys end ! def ransackable_associations(auth_object = nil) reflect_on_all_associations.map { |a| a.name.to_s } end

Slide 49

Slide 49 text

…fall in love with metaprogramming Don’t...

Slide 50

Slide 50 text

…fall in love with metaprogramming Don’t...

Slide 51

Slide 51 text

…fall in love with metaprogramming Don’t...

Slide 52

Slide 52 text

YOU CAN NOT HAS BUCKET OF METHODS if Class < Module puts 'That goes for you too, Class.' end

Slide 53

Slide 53 text

module MetaSearch module Utility #:nodoc: ! TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set ! private ! def preferred_method_name(method_id) method_name = method_id.to_s where = Where.new(method_name) rescue nil return nil unless where where.aliases.each do |a| break if method_name.sub!(/#{a}(=?)$/, "#{where.name}\\1") end method_name end ! def array_of_strings?(o) o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)} end ! def array_of_arrays?(vals) vals.is_a?(Array) && vals.first.is_a?(Array) end ! def array_of_dates?(vals) vals.is_a?(Array) && vals.first.respond_to?(:to_time) end ! def cast_attributes(type, vals) if array_of_arrays?(vals) vals.map! {|v| cast_attributes(type, v)} # Need to make sure not to kill multiparam dates/times elsif vals.is_a?(Array) && (array_of_dates?(vals) || !(DATES+TIMES).include?(type)) vals.map! {|v| cast_attribute(type, v)} else cast_attribute(type, vals)

Slide 54

Slide 54 text

when :integer val.blank? ? nil : val.to_i when :float val.blank? ? nil : val.to_f when :decimal if val.blank? nil elsif val.class == BigDecimal val elsif val.respond_to?(:to_d) val.to_d else val.to_s.to_d end else raise TypeCastError, "Unable to cast columns of type #{type}" end end ! def collapse_multiparameter_options(opts) opts.keys.each do |k| if k.include?("(") real_attribute, position = k.split(/\(|\)/) cast = %w(a s i).include?(position.last) ? position.last : nil position = position.to_i - 1 value = opts.delete(k) opts[real_attribute] ||= [] opts[real_attribute][position] = if cast (value.blank? && cast == 'i') ? nil : value.send("to_#{cast}") else value end end end opts end end end

Slide 55

Slide 55 text

…put your code in “buckets” Don’t...

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

…hitch your cart to someone else’s horse Don’t...

Slide 58

Slide 58 text

MediaWiki schema, image by Nick Jenkins

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

…think of your app as “a Rails app” Don’t...

Slide 61

Slide 61 text

require 'delegate' ! class Auditor < SimpleDelegator attr_reader :user, :record ! def initialize(user, record) @user, @record = user, record super(record) end ! def class @record.class end ! def update_attributes(attributes, options = {}) with_transaction_returning_status do assign_attributes(attributes, options) save end end ! def save(*) action = @record.persisted? ? 'update' : 'create' super.tap { |success| success && log_action(action) } end ! def destroy super.tap { |record| record && log_action('destroy') } end ! # ... ! end

Slide 62

Slide 62 text

require 'delegate' ! class Auditor < SimpleDelegator attr_reader :user, :record ! def initialize(user, record) @user, @record = user, record super(record) end ! def class @record.class end ! def update_attributes(attributes, options = {}) with_transaction_returning_status do assign_attributes(attributes, options) save end end ! def save(*) action = @record.persisted? ? 'update' : 'create' super.tap { |success| success && log_action(action) } end ! def destroy super.tap { |record| record && log_action('destroy') } end ! # ... ! end

Slide 63

Slide 63 text

def render(&block) options = @options.stringify_keys tag_value = options.delete("value") name_and_id = options.dup ! if name_and_id["for"] name_and_id["id"] = name_and_id["for"] else name_and_id.delete("id") end ! add_default_name_and_id_for_value(tag_value, name_and_id) options.delete("index") options.delete("namespace") options["for"] = name_and_id["id"] unless options.key?("for") ! if block_given? content = @template_object.capture(&block) else content = if @content.blank? @object_name.gsub!(/\[(.*)_attributes\]\[\d+\]/, '.\1') method_and_value = tag_value.present? ? "#{@method_name}.#{tag_value}" : @method_name ! if object.respond_to?(:to_model) key = object.class.model_name.i18n_key i18n_default = ["#{key}.#{method_and_value}".to_sym, ""] end ! i18n_default ||= "" I18n.t("#{@object_name}.#{method_and_value}", :default => i18n_default, :scope => "helpers.label").presence else @content.to_s end ! content ||= if object && object.class.respond_to?(:human_attribute_name) object.class.human_attribute_name(@method_name) end ! content ||= @method_name.humanize end ! label_tag(name_and_id["id"], content, options) end action_view/helpers/tags/label.rb

Slide 64

Slide 64 text

def render(&block) options = @options.stringify_keys tag_value = options.delete("value") name_and_id = options.dup ! if name_and_id["for"] name_and_id["id"] = name_and_id["for"] else name_and_id.delete("id") end ! add_default_name_and_id_for_value(tag_value, name_and_id) options.delete("index") options.delete("namespace") options["for"] = name_and_id["id"] unless options.key?("for") ! if block_given? content = @template_object.capture(&block) else content = if @content.blank? @object_name.gsub!(/\[(.*)_attributes\]\[\d+\]/, '.\1') method_and_value = tag_value.present? ? "#{@method_name}.#{tag_value}" : @method_name ! if object.respond_to?(:to_model) key = object.class.model_name.i18n_key i18n_default = ["#{key}.#{method_and_value}".to_sym, ""] end ! i18n_default ||= "" I18n.t("#{@object_name}.#{method_and_value}", :default => i18n_default, :scope => "helpers.label").presence else @content.to_s end ! content ||= if object && object.class.respond_to?(:human_attribute_name) object.class.human_attribute_name(@method_name) end ! content ||= @method_name.humanize end ! label_tag(name_and_id["id"], content, options) end action_view/helpers/tags/label.rb

Slide 65

Slide 65 text

if object.respond_to?(:to_model) key = object.class.model_name.i18n_key i18n_default = ["#{key}.#{method_and_value}".to_sym, ""] end

Slide 66

Slide 66 text

if object.respond_to?(:to_model) key = object.class.model_name.i18n_key i18n_default = ["#{key}.#{method_and_value}".to_sym, ""] end (more like LOL of Demeter, amirite?)

Slide 67

Slide 67 text

class PostsController < ApplicationController ! # ... ! def edit @post = Auditor.new(current_user, Post.find(params[:id])) end ! # ... ! end <%= link_to 'Comments', post_comments_path(@post) %>

Slide 68

Slide 68 text

class PostsController < ApplicationController ! # ... ! def edit @post = Auditor.new(current_user, Post.find(params[:id])) end ! # ... ! end <%= link_to 'Comments', post_comments_path(@post) %> /posts/1/comments/?post_id=1

Slide 69

Slide 69 text

def generate key, name, options, recall = {}, parameterize = nil constraints = recall.merge options ! match_route(name, constraints) do |route| data = constraints.dup ! keys_to_keep = route.parts.reverse.drop_while { |part| !options.key?(part) || (options[part] || recall[part]).nil? } | route.required_parts ! (data.keys - keys_to_keep).each do |bad_key| data.delete bad_key end ! parameterized_parts = data.dup ! if parameterize parameterized_parts.each do |k,v| parameterized_parts[k] = parameterize.call(k, v) end end ! parameterized_parts.keep_if { |_,v| v } ! next if !name && route.requirements.empty? && route.parts.empty? ! next unless verify_required_parts!(route, parameterized_parts) ! z = Hash[options.to_a - data.to_a - route.defaults.to_a] ! return [route.format(parameterized_parts), z] end ! raise Router::RoutingError end

Slide 70

Slide 70 text

def generate key, name, options, recall = {}, parameterize = nil constraints = recall.merge options ! match_route(name, constraints) do |route| data = constraints.dup ! keys_to_keep = route.parts.reverse.drop_while { |part| !options.key?(part) || (options[part] || recall[part]).nil? } | route.required_parts ! (data.keys - keys_to_keep).each do |bad_key| data.delete bad_key end ! parameterized_parts = data.dup ! if parameterize parameterized_parts.each do |k,v| parameterized_parts[k] = parameterize.call(k, v) end end ! parameterized_parts.keep_if { |_,v| v } ! next if !name && route.requirements.empty? && route.parts.empty? ! next unless verify_required_parts!(route, parameterized_parts) ! z = Hash[options.to_a - data.to_a - route.defaults.to_a] ! return [route.format(parameterized_parts), z] end ! raise Router::RoutingError end

Slide 71

Slide 71 text

…assume too much about how others will use your objects Don’t...

Slide 72

Slide 72 text

def eql?(other) self.class == other.class && self.user == other.user && self.record == other.record end alias :== :eql?

Slide 73

Slide 73 text

No content

Slide 74

Slide 74 text

…use ActiveRecord callbacks, if you can help it Don’t...

Slide 75

Slide 75 text

…use ActiveRecord callbacks, if you can help it Don’t... (you can almost always help it)

Slide 76

Slide 76 text

before_save!!! class User < ActiveRecord::Base def create_or_update say_my_name && super end ! def say_my_name puts "My name is #{name}"; true end end

Slide 77

Slide 77 text

before_save!!! class User < ActiveRecord::Base def create_or_update say_my_name && super end ! def say_my_name puts "My name is #{name}"; true end end

Slide 78

Slide 78 text

after_save!!! class User < ActiveRecord::Base def create_or_update super && final_stuff or raise ActiveRecord::Rollback end ! def final_stuff puts "IMPORTANT FINAL STUFF" end end

Slide 79

Slide 79 text

after_save!!! class User < ActiveRecord::Base def create_or_update super && final_stuff or raise ActiveRecord::Rollback end ! def final_stuff puts "IMPORTANT FINAL STUFF" end end

Slide 80

Slide 80 text

around_save!!! class User < ActiveRecord::Base def create_or_update puts "GET READY" unless sneak_attack? super puts "WASN'T THAT EXCITING?" if awesome? end end

Slide 81

Slide 81 text

around_save!!! class User < ActiveRecord::Base def create_or_update puts "GET READY" unless sneak_attack? super puts "WASN'T THAT EXCITING?" if awesome? end end

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

No content

Slide 84

Slide 84 text

Me (sort of)

Slide 85

Slide 85 text

…mistake the illusion of accomplishment for the real thing Don’t...

Slide 86

Slide 86 text

Photo by Tim Baker http://www.flickr.com/photos/timmygunz/

Slide 87

Slide 87 text

…accept! counter-offers Don’t...

Slide 88

Slide 88 text

No content

Slide 89

Slide 89 text

…take a job for the money Don’t...

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

Photo by Robbert van der Steeg

Slide 93

Slide 93 text

…assume it’s too late Don’t...

Slide 94

Slide 94 text

No content

Slide 95

Slide 95 text

…get comfortable Don’t...

Slide 96

Slide 96 text

No content

Slide 97

Slide 97 text

No content

Slide 98

Slide 98 text

No content

Slide 99

Slide 99 text

Not me.

Slide 100

Slide 100 text

Not me. Also not me.

Slide 101

Slide 101 text

Stepdaughter, clearly acknowledging my coolness.

Slide 102

Slide 102 text

No content

Slide 103

Slide 103 text

No content

Slide 104

Slide 104 text

…try to be someone you’re not Don’t...

Slide 105

Slide 105 text

No content

Slide 106

Slide 106 text

…be afraid Don’t...

Slide 107

Slide 107 text

No content

Slide 108

Slide 108 text

…be afraid to say no Don’t...

Slide 109

Slide 109 text

Philippe Faraut, “La Fille du Marin”

Slide 110

Slide 110 text

No content

Slide 111

Slide 111 text

Employee.where(:slacker => true).values_of :first_name, :last_name, :hired_at # => [["Ernie", "Miller", 2009-09-21 08:00:00 -0400], ...] ! class Animal < ActiveRecord::Base serialize :extra_info end ! Animal.where(:genus => 'felis').values_of :species, :extra_info # => [["catus", {:domestic => true}], ["lolcatus", {:can_has_cheezburger => true}], ...] Valium https://github.com/ernie/valium

Slide 112

Slide 112 text

“I've had times where I would just fork off a child process, do all the memory-intensive stuff inside the child process (1000+ AR objects would be instantiated) and then kill off the child when it was finished to remove potential memory leaks.” — A commenter

Slide 113

Slide 113 text

No content

Slide 114

Slide 114 text

No content

Slide 115

Slide 115 text

No content

Slide 116

Slide 116 text

No content

Slide 117

Slide 117 text

No content

Slide 118

Slide 118 text

…be afraid to share Don’t...

Slide 119

Slide 119 text

No content

Slide 120

Slide 120 text

…be afraid to speak Don’t...

Slide 121

Slide 121 text

No content

Slide 122

Slide 122 text

SEEK ACCOUNTABILITY

Slide 123

Slide 123 text

No content

Slide 124

Slide 124 text

…be afraid to stretch Don’t...

Slide 125

Slide 125 text

THANKS!

Slide 126

Slide 126 text

❤️ THANKS!