SlideShare a Scribd company logo
Michael Mahlberg, Consulting Guild AG
Jens-Christian Fischer, InVisible GmbH

SOLID Ruby -
SOLID Rails
Establishing a sustainable
codebase
Who?

       Michael Mahlberg
Founder of

     roughly a dozen companies
     over the last two decades
SOLID Ruby, SOLID Rails

Recommended for you

Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails

Migrations allow you to define and manage changes to your database schema over time. The document discusses ActiveRecord migrations, which provide a way to iteratively improve the database schema by adding, removing, and changing tables and columns. It also covers generating and rolling back migrations, common migration methods like create_table and add_column, and using migrations to support models and testing.

active recordunit testingruby on rails
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007

Active Record is an object-relational mapping pattern that allows mapping database tables to object classes. It uses the principle of "convention over configuration" to minimize configuration work. The Active Record pattern is implemented in Ruby on Rails through the ActiveRecord library, which provides methods for CRUD operations and associations between models. It aims to make working with databases and ORM intuitive for developers.

Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7

This document provides an introduction to the Ruby programming language. It discusses Ruby's object-oriented nature, dynamic typing, syntax similarities to other languages like Java and C#, and the ease of learning Ruby. It also demonstrates simple Ruby code examples for arrays, hashes, classes, inheritance and modules. Testing practices like TDD (test-driven development) are emphasized. Popular Ruby web frameworks like Ruby on Rails, Sinatra and libraries like HAML and SASS are also introduced.

ruby tccc7
>> relevance
=> nil
Working as

     A consultant on software
     processes, architecture &
     design for > 2 decades
SOLID Ruby, SOLID Rails
>> relevance != nil
=> true

Recommended for you

Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code

Most PHP developers focus on writing code. But creating Web applications is about much more than just wrting PHP. Take a step outside the PHP cocoon and into the big PHP ecosphere to find out how small code changes can make a world of difference on servers and network. This talk is an eye-opener for developers who spend over 80% of their time coding, debugging and testing.

php ecosystemnetworkingphp
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift

Apple's Swift has achieved the top place in Stack Overflow's "Most Loved" list of programming languages in its 2015 Developer Survey. Based on information gleaned from GitHub and Stack Overflow, analyst firm RedMonk has seen Swift's popularity ranking soar from 68 to 22 in an unprecedented 6 months. The "Extreme Swift" event does not require advanced, or even any, knowledge of Swift. Learn about some of the more outrageous features of the language which help explain what the fuss is all about! Never look at programming the same way again — even if you never end up writing a single line of Swift code in your life.

appleiosipad
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel

This document discusses building web service clients with ActiveModel. It notes that ActiveModel is used for building forms and interacting with data internally within requests. It then discusses how to abstract complexity when working with web services and external APIs. It provides examples of using ActiveModel features like callbacks, dirty tracking, errors, serialization, and validations to build client-side models. It also discusses techniques for making parallel API requests using libraries like EventMachine and Typhoeus to improve performance. The goal is to build readable and maintainable client-side code that can scale with both complexity and team size.

goruco2010ruby on railsruby
Who?

       Jens-Christian Fischer
Tinkerer, Practician,
      Author
            and generally
          interested in way
           too many things
What is
SOLID?
SOLID
  is
 not
  a
 Law

Recommended for you

Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel

This document discusses building web service clients with ActiveModel. It notes that ActiveModel provides attributes, callbacks, dirty tracking, errors handling, serialization and validations to make client code more readable and maintainable. It recommends using parallel connections and asynchronous libraries like EventMachine and Typhoeus for efficiency. Examples show defining requests in a threaded pool for concurrency. The goal is to abstract complexity, scale well with complexity and team size, and make stubbing easy for development.

rails3activemodelruby on rails
Rails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not KnowRails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not Know

I gave a talk at Rails World 2023 in Amsterdam on Powerful Rails Features You Might Not Know. If all you've got is a hammer, everything looks like a nail. In tech, there is a constant stream of new features being added every day. Keeping up with the latest Ruby on Rails functionality can help you and your team be far more productive than you might normally be. In this talk, we walk through a bunch of lesser known or easy to miss features in Ruby on Rails that you can use to improve your skills.

railsrubyrailsworld
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo

ruby on rails training session #2: 1) how to add login/logout/signup functions; 2) a functional/unit test; 3) simple ajax to post a weibo.

PPP
(by Robert C. Martin)




                        Agile Software
                        Development,
                        Principles, Patterns,
                        and Practices
Principles!

        You know - more
         like guidelines
SOLID
SOLID

SRP OCP L
S   O   LSP I
            ISP DIP
                D

Recommended for you

Beyond php it's not (just) about the code
Beyond php   it's not (just) about the codeBeyond php   it's not (just) about the code
Beyond php it's not (just) about the code

The document discusses database queries and optimization. It begins with an example of a complex database query and explains how to detect problematic queries using tools like slow query log and pt-query-digest. It then discusses indexing strategies and when to use indexes. The document also describes a case study of a client's jobs search site that was experiencing high database load due to inefficient queries in a loop, and how batching the queries into a single query solved the problem.

phpconplnetworkingmysql
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007

Active Record is an object-relational mapping (ORM) pattern that allows developers to interact with a database using objects rather than SQL queries. It establishes a direct association between classes and database tables, and between class objects and table rows. The key characteristics of Active Record include directly mapping classes to tables, objects to rows, and using finders and setters to encapsulate data access. The Ruby on Rails framework includes an implementation of Active Record to provide data modeling and database access functions.

ruby
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager

The document discusses tools for managing form data and validation. It introduces Data::Manager, which provides a way to manage incoming data and validation rules across multiple scopes or sections. Data::Manager uses Data::Verifier under the hood to validate data according to defined rules. It provides methods to verify data, check for errors, and retrieve validation results. The document emphasizes usability, reliability, and hiding complexity through a clean API.

software developmentweb design and development
S OL I D

SRP OCP LSP ISP DIP
SRP
SRP
      Single
      Responsibility
      Principle
SRP
      Single
      Responsibility
      Principle


                   A class should have
                   one, and only one,
                   reason to change.

Recommended for you

Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013

Esta palestra apresentará as funcionalidades disponibilizadas pelo framework web Ruby on Rails desde sua primeira versão até o Rails 4. Serão apresentadas as evoluções mais significativas de cada release e as principais características do Rails 4. Ruby on Rails tem se tornado cada vez mais popular e ganhado mais adeptos. Sempre ouço comentários de desenvolvedores de outras tecnologias que desejam conhecer melhor o framework, seja para implementar projetos pessoais ou mesmo dar um novo rumo na vida profissional. Acredito que uma apresentação das evoluções implementas nesta tecnologia permitirá que muitos desenvolvedores e entusiatas obtenham um conhecimento básico, o que facilitará seus estudos posteriores permitindo que possam aprofundar mais em cada tópico coberto na palestra. A palestra não tem o objetivo de entrar em detalhes técnicos das implementações, mas sim explicar e, sempre que possível exemplificar, o que passou a ser possível de ser implementado após cada release.

software developmentruby on railsruby
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)

Introductionary talk and tutorial on Groovy, discussion of its success and popularity, issues with the future of Java with examples

SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps

Mike Subelsky of OtherInbox.com discusses the SproutCore JavaScript framework for building desktop web applications that run inside the browser.

sproutcorejavascriptframework
User Class
require 'digest/sha1'

class User < ActiveRecord::Base
 include Authentication
 include Authentication::ByPassword
 include Authentication::ByCookieToken

 #TODO Check login redirect if this filter is skipped
 #skip_after_filter :store_location

 # Virtual attribute for the unencrypted password
 attr_accessor :password

 belongs_to :country

 has_one :user_profile, :dependent => :destroy
 has_one :note

 has_many   :queries
 has_many   :tags, :foreign_key => "created_by"
 has_many   :taggings, :as => :tagger
 has_many   :organizations, :through => :affiliations
 has_many   :affiliations
 has_many   :locations, :through => :affiliations
 has_many   :projects, :through => :memberships
 has_many   :memberships
 has_many   :public_assets, :through => :privileges
 has_many   :descriptions, :through => :privileges
 has_many   :assessments, :through => :privileges
 has_many   :description_profiles, :through => :privileges
 has_many   :privileges
 has_many   :diaries
 has_many   :roles, :through => :commitments
 has_many   :commitments
 has_many   :activities
 has_many   :messages
 has_many   :fellowships
end

def editable_by?(user=nil)
 self.created_by == user
end

def readable_by?(user=nil)
 self.created_by == user
end

def boards
                               User Class
 Board.all :conditions => { :user_group_id => self.user_groups.collect{ |g| g.id }}
end

def discussions
 Discussion.all :conditions => { :board_id => self.boards.collect{ |b| b.id }}
end

def organization_roles
 role_ids = Affiliation.all(:conditions => {:user_id => self.id}).collect{|a| a.role_id}.uniq
 roles = Role.find(role_ids)
end

def user_group_roles
 role_ids = Fellowship.all(:conditions => {:user_id => self.id}).collect{|a| a.role_id}.uniq
 roles = Role.find(role_ids)
end

def project_roles
 role_ids = Membership.all(:conditions => {:user_id => self.id}).collect{|a| a.role_id}.uniq
 roles = Role.find(role_ids)
end

def all_roles
 roles = (self.organization_roles + self.user_group_roles + self.project_roles).uniq
end

def tags_of(user)
 taggings = Tagging.all :conditions => {:taggable_type => "User", :taggable_id => self.id, :tagger_type => "User", :tagge
 tags = taggings.collect {|t| t.tag.name}.uniq.sort
end
So what‘s wrong with
        this?
From: user.rb

Recommended for you

Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010

Palestra do Rs On Rails, na qual demos algumas dicas de boas práticas para manter seu código mais limpo e ter absoluto controle da sua aplicação em produção.

good practicesruby on railsruby
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails

Ruby is a dynamic, open source programming language that is interpreted, object-oriented, and functional. It focuses on simplicity and emphasizes programmer productivity. Ruby on Rails is a web application framework built on Ruby that follows the model-view-controller architectural pattern. It aims to make web development faster and easier through its conventions, including generating scaffolding for basic CRUD operations on models.

Beyond HTML Internet Briefing
Beyond HTML Internet BriefingBeyond HTML Internet Briefing
Beyond HTML Internet Briefing

Früher war alles besser - sowieso! Konnte man vor 20 Jahren alleine mit HTML einen Webauftritt gestalten, hat sich die Anzahl der Technologien, die eine Webentwicklerin beherrschen muss, ... Vortrag am Internet Briefing in Zürich, 4.12.2012

htmlcsstools
From: user.rb
class User < ActiveRecord::Base
  include Authentication
  include Authentication::ByPassword
  include Authentication::ByCookieToken
...
 belongs_to :country
...
  has_one :user_profile, :dependent => :destroy
 has_many :queries
  has_many :tags, :foreign_key => "created_by"
...
  validates_presence_of     :login, :email, :country_id
  validates_presence_of     :password, :if => :password_required?
...
From: user.rb
From: user.rb
 acts_as_state_machine :initial => :pending

  state :pending, :enter => :make_activation_code
  state :active, :enter => :do_activate
...
  event :register do
    transitions :from => :passive, :to => :pending, :guard =>
Proc.new {|u| !(u.crypted_password.blank? &&
u.password.blank?) }
  end
...
  def message_threads
    self.message_threads + self.message_threads
  end
From: user.rb

Recommended for you

Beyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehr
Beyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehrBeyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehr
Beyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehr

Früher war alles besser - sowieso! Konnte man vor 20 Jahren alleine mit HTML einen Webauftritt gestalten, hat sich die Anzahl der Technologien, die eine Webentwicklerin beherrschen muss, vervielfacht. Was ist wichtig, was unwichtig? In diesem Vortrag beleuchtet Jens-Christian den aktuellen Zoo von Technologien, und zeigt auf, wie sich diese Vielfalt sinnvoll bändigen lässt. HTML(5), CSS(3), JavaScript, CoffeeScript, JavaScript Frameworks (jQuery, Prototype, Moo, Dojo, Ext, ...), JavaScript Microframeworks (Backbone, Ember, Flatiron), Templatingsprachen, Hilfsmittel zur Gestaltung von CSS (SASS, SCSS), Responsive Design, Browsererkennung, Caching, Performancetweaks, Testing und vieles mehr wird thematisiert.

htmlframeworkshaml
Architektur der kleinen Bausteine
Architektur der kleinen BausteineArchitektur der kleinen Bausteine
Architektur der kleinen Bausteine

Betrachtungen zur Architektur von Software Systemen.

soaprestservice-oriented architecture
Taking your Web App for a walk
Taking your Web App for a walkTaking your Web App for a walk
Taking your Web App for a walk

What strategies can you take to bring a web application to a mobile device? Six steps from pure HTML/CSS all the way to almost native applications.

titaniumjquery mobilesencha
From: user.rb
  def forum_nickname
    self.user_profile.nickname.blank? ? "#{self.first_name}
#{self.last_name}" : self.user_profile.nickname
  end

  def name
    "#{self.first_name} #{self.last_name}" rescue 'n/a'
  end

  def email_with_name
    "#{self.first_name} #{self.last_name} <#{self.email}>"
  end
From: user.rb
From: user.rb
def is_admin?
  self.roles.collect{|role| role.title}.include?('admin')
end

def countries
  [self.country]
end
From: user.rb

Recommended for you

Mobino at Webmondy Frankfurt, Mai 2011
Mobino at Webmondy Frankfurt, Mai 2011Mobino at Webmondy Frankfurt, Mai 2011
Mobino at Webmondy Frankfurt, Mai 2011

Introduction to Mobino, a mobile payment service. Held at WebMonday Frankfurt, Mai 2011

mobino"mobile payment"
Testing distributed, complex web applications
Testing distributed, complex web applicationsTesting distributed, complex web applications
Testing distributed, complex web applications

As applications grow from single Rails applications to complex systems with multiple, interacting applications & web services, testing becomes more and more difficult. While we can test each application independently, we need to be able to test the full stack. This presentation shows methods, tools and tipps & tricks from testing such a complex application.

railswayconrailstesting
Ruby Coding Dojo
Ruby Coding DojoRuby Coding Dojo
Ruby Coding Dojo

This document discusses coding dojos and katas. It explains that katas are choreographed coding exercises used to practice skills through repetition. Coding dojos are places where developers practice katas in pairs and groups using a randori style. This document provides an example kata involving opening 100 doors with multiple monkeys and demonstrates the kata being practiced in a coding dojo.

railswayconkatarwc10
From: user.rb
 def boards
    Board.all :conditions => { :user_group_id =>
self.user_groups.collect{ |g| g.id }}
  end

  def discussions
    Discussion.all :conditions => { :board_id =>
self.boards.collect{ |b| b.id }}
  end

  def organization_roles
    role_ids = Affiliation.all(:conditions => {:user_id =>
self.id}).collect{|a| a.role_id}.uniq
    roles = Role.find(role_ids)
  end
From: user.rb
From: user.rb
  def make_password_reset_code
    self.password_reset_code =
Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by
{rand}.join )
  end

  def self.published_users
    User.all(:conditions => ['state = ?',
'published'], :order => 'login ASC', :include =>
[:user_profile])
  end
Anyone notice a pattern?

Recommended for you

Synology Workshop07 06
Synology Workshop07 06Synology Workshop07 06
Synology Workshop07 06

Workshop über Synology NAS bei Alltron AG, Mägenwil

Offline Arbeiten
Offline ArbeitenOffline Arbeiten
Offline Arbeiten

Rails Applikationen Offline nehmen. Ein Überblick über Techniken und vertiefte Betrachtung zu Joyent Slingshot

Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation

Manual Method of Product Research | Helium10 | MBS RETRIEVER

product researchhelium10 | mbs retriever
Neither do we
Separation of Concerns
Authentication
    Roles
   Mailers
    State
     ...
So how?


  Mixins

Recommended for you

INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf

These fighter aircraft have uses outside of traditional combat situations. They are essential in defending India's territorial integrity, averting dangers, and delivering aid to those in need during natural calamities. Additionally, the IAF improves its interoperability and fortifies international military alliances by working together and conducting joint exercises with other air forces.

air force fighter planebiggest submarinezambia port
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx

Revolutionize your transportation processes with our cutting-edge RPA software. Automate repetitive tasks, reduce costs, and enhance efficiency in the logistics sector with our advanced solutions.

rpa in transportationrpa in transportation industryrpa in transportation sector
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf

Profile portofolio

New User Model
New User Model
class User < ActiveRecord::Base
  include Authentication
  include Authentication::ByPassword
  include Authentication::ByCookieToken

  include   Project::UserStates
  include   Project::UserMailer
  include   Project::UserForum
  include   Project::UserMessages
...
end
UserMessages
UserMessages
module Project
  module UserMessages
    # to be included in User Model

    has_many :messages
    def message_threads
      MessageThread.all(:conditions =>
        ["sender_id = ? or receiver_id = ?",
          self.id, self.id])
  end
end
end

Recommended for you

Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops

This presentation, delivered at the Postgres Bangalore (PGBLR) Meetup-2 on June 29th, 2024, dives deep into connection pooling for PostgreSQL databases. Aakash M, a PostgreSQL Tech Lead at Mydbops, explores the challenges of managing numerous connections and explains how connection pooling optimizes performance and resource utilization. Key Takeaways: * Understand why connection pooling is essential for high-traffic applications * Explore various connection poolers available for PostgreSQL, including pgbouncer * Learn the configuration options and functionalities of pgbouncer * Discover best practices for monitoring and troubleshooting connection pooling setups * Gain insights into real-world use cases and considerations for production environments This presentation is ideal for: * Database administrators (DBAs) * Developers working with PostgreSQL * DevOps engineers * Anyone interested in optimizing PostgreSQL performance Contact info@mydbops.com for PostgreSQL Managed, Consulting and Remote DBA Services

postgresqlpgsqldatabase
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In

Six months into 2024, and it is clear the privacy ecosystem takes no days off!! Regulators continue to implement and enforce new regulations, businesses strive to meet requirements, and technology advances like AI have privacy professionals scratching their heads about managing risk. What can we learn about the first six months of data privacy trends and events in 2024? How should this inform your privacy program management for the rest of the year? Join TrustArc, Goodwin, and Snyk privacy experts as they discuss the changes we’ve seen in the first half of 2024 and gain insight into the concrete, actionable steps you can take to up-level your privacy program in the second half of the year. This webinar will review: - Key changes to privacy regulations in 2024 - Key themes in privacy and data governance in 2024 - How to maximize your privacy program in the second half of 2024

data privacyprivacy complianceai
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck

YOUR RELIABLE WEB DESIGN & DEVELOPMENT TEAM — FOR LASTING SUCCESS WPRiders is a web development company specialized in WordPress and WooCommerce websites and plugins for customers around the world. The company is headquartered in Bucharest, Romania, but our team members are located all over the world. Our customers are primarily from the US and Western Europe, but we have clients from Australia, Canada and other areas as well. Some facts about WPRiders and why we are one of the best firms around: More than 700 five-star reviews! You can check them here. 1500 WordPress projects delivered. We respond 80% faster than other firms! Data provided by Freshdesk. We’ve been in business since 2015. We are located in 7 countries and have 22 team members. With so many projects delivered, our team knows what works and what doesn’t when it comes to WordPress and WooCommerce. Our team members are: - highly experienced developers (employees & contractors with 5 -10+ years of experience), - great designers with an eye for UX/UI with 10+ years of experience - project managers with development background who speak both tech and non-tech - QA specialists - Conversion Rate Optimisation - CRO experts They are all working together to provide you with the best possible service. We are passionate about WordPress, and we love creating custom solutions that help our clients achieve their goals. At WPRiders, we are committed to building long-term relationships with our clients. We believe in accountability, in doing the right thing, as well as in transparency and open communication. You can read more about WPRiders on the About us page.

web development agencywpriderswordpress development
Methods
SOLID Ruby, SOLID Rails
def transfer(data, url)
  h = Net::HTTP.new(self.uri.host, self.uri.port)
  RAILS_DEFAULT_LOGGER.debug "connecting to CL: #{self.uri}"
  RAILS_DEFAULT_LOGGER.debug "connecting to CL: #{url}"

  resp = h.post(url, data, {'Content-Type' => 'application/xml'})
  response_code = resp.code.to_i
  location = if response_code == 201
    resp['Location']
  else
    RAILS_DEFAULT_LOGGER.debug "error from CL: #{response_code}"
    RAILS_DEFAULT_LOGGER.debug "error from CL: #{resp.body}"
    @error = resp.body
    nil
  end
  [response_code, location]
end
SOLID Ruby, SOLID Rails

Recommended for you

UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference

We are honored to launch and host this event for our UiPath Polish Community, with the help of our partners - Proservartner! We certainly hope we have managed to spike your interest in the subjects to be presented and the incredible networking opportunities at hand, too! Check out our proposed agenda below 👇👇 08:30 ☕ Welcome coffee (30') 09:00 Opening note/ Intro to UiPath Community (10') Cristina Vidu, Global Manager, Marketing Community @UiPath Dawid Kot, Digital Transformation Lead @Proservartner 09:10 Cloud migration - Proservartner & DOVISTA case study (30') Marcin Drozdowski, Automation CoE Manager @DOVISTA Pawel Kamiński, RPA developer @DOVISTA Mikolaj Zielinski, UiPath MVP, Senior Solutions Engineer @Proservartner 09:40 From bottlenecks to breakthroughs: Citizen Development in action (25') Pawel Poplawski, Director, Improvement and Automation @McCormick & Company Michał Cieślak, Senior Manager, Automation Programs @McCormick & Company 10:05 Next-level bots: API integration in UiPath Studio (30') Mikolaj Zielinski, UiPath MVP, Senior Solutions Engineer @Proservartner 10:35 ☕ Coffee Break (15') 10:50 Document Understanding with my RPA Companion (45') Ewa Gruszka, Enterprise Sales Specialist, AI & ML @UiPath 11:35 Power up your Robots: GenAI and GPT in REFramework (45') Krzysztof Karaszewski, Global RPA Product Manager 12:20 🍕 Lunch Break (1hr) 13:20 From Concept to Quality: UiPath Test Suite for AI-powered Knowledge Bots (30') Kamil Miśko, UiPath MVP, Senior RPA Developer @Zurich Insurance 13:50 Communications Mining - focus on AI capabilities (30') Thomasz Wierzbicki, Business Analyst @Office Samurai 14:20 Polish MVP panel: Insights on MVP award achievements and career profiling

#uipathcommunity#automation#automationdeveloper
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf

Solar Storms (Geo Magnetic Storms) are the motion of accelerated charged particles in the solar environment with high velocities due to the coronal mass ejection (CME).

solar storms
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx

This is a slide deck that showcases the updates in Microsoft Copilot for May 2024

microsoftmicrosoft copilot
def transfer(data, document)

  if document.cl_document_url != nil
    self.uri = URI.parse(document.cl_document_url )
    h = Net::HTTP.new(self.uri.host, self.uri.port)
    response = h.post(self.uri, data, {'Content-Type' =>
'application/xml'})
  else
    h = Net::HTTP.new(self.uri.host, self.uri.port)
    response = h.post("/tasks", data, {'Content-Type' =>
'application/xml'})
  end
  response_code = response.code.to_i
  if response_code == 201
    location = response['Location']
    document.cl_document_url = location
    document.save!
  else
    nil
  end
  [response_code, location]
end
def transfer(data, document)

  if document.cl_document_url != nil
    self.uri = URI.parse(document.cl_document_url )
    h = Net::HTTP.new(self.uri.host, self.uri.port)
    response = h.post(self.uri, data, {'Content-Type' =>
'application/xml'})
  else
    h = Net::HTTP.new(self.uri.host, self.uri.port)
    response = h.post("/tasks", data, {'Content-Type' =>
'application/xml'})
  end
  response_code = response.code.to_i
  if response_code == 201
    location = response['Location']
    document.cl_document_url = location
    document.save!
  else
    nil
  end
  [response_code, location]
end
SRP Transfer
SRP Transfer
def transfer data
  open_connection
  post data
  return location
end

def open_connection
  @http = Net::HTTP.new(self.uri.host, self.uri.port)
end

def post data
  @response = http.post(self.url, data, {'Content-Type' =>
                                         'application/xml'})
end

Recommended for you

The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing

Invited Remote Lecture to SC21 The International Conference for High Performance Computing, Networking, Storage, and Analysis St. Louis, Missouri November 18, 2021

distributed supercomputerdistributed machine learning
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection

Cybersecurity is a major concern in today's connected digital world. Threats to organizations are constantly evolving and have the potential to compromise sensitive information, disrupt operations, and lead to significant financial losses. Traditional cybersecurity techniques often fall short against modern attackers. Therefore, advanced techniques for cyber security analysis and anomaly detection are essential for protecting digital assets. This blog explores these cutting-edge methods, providing a comprehensive overview of their application and importance.

cybersecurityanomaly detectionadvanced techniques
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf

Presented at Gartner Data & Analytics, London Maty 2024. BT Group has used the Neo4j Graph Database to enable impressive digital transformation programs over the last 6 years. By re-imagining their operational support systems to adopt self-serve and data lead principles they have substantially reduced the number of applications and complexity of their operations. The result has been a substantial reduction in risk and costs while improving time to value, innovation, and process automation. Join this session to hear their story, the lessons they learned along the way and how their future innovation plans include the exploration of uses of EKG + Generative AI.

neo4jneo4j webinarsgraph database
SOLID Ruby, SOLID Rails
def location
  get_location if created? # returns nil if not created?
end

def response_code
  @response.code.to_i
end

def created?
  response_code == 201
end

def get_location
  @response['Location']
end

def error
  @response.body
end
Add a 16-band
 equalizer & a
   BlueRay®
player to this...
And now to
  this...

Recommended for you

BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL

Blockchain technology is transforming industries and reshaping the way we conduct business, manage data, and secure transactions. Whether you're new to blockchain or looking to deepen your knowledge, our guidebook, "Blockchain for Dummies", is your ultimate resource.

blockchainweb3blockchain technology
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence

Our Linux Web Hosting plans offer unbeatable performance, security, and scalability, ensuring your website runs smoothly and efficiently. Visit- https://onliveserver.com/linux-web-hosting/

cheap linux hosting
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world

The presentation showcases the diverse real-world applications of Fused Deposition Modeling (FDM) across multiple industries: 1. **Manufacturing**: FDM is utilized in manufacturing for rapid prototyping, creating custom tools and fixtures, and producing functional end-use parts. Companies leverage its cost-effectiveness and flexibility to streamline production processes. 2. **Medical**: In the medical field, FDM is used to create patient-specific anatomical models, surgical guides, and prosthetics. Its ability to produce precise and biocompatible parts supports advancements in personalized healthcare solutions. 3. **Education**: FDM plays a crucial role in education by enabling students to learn about design and engineering through hands-on 3D printing projects. It promotes innovation and practical skill development in STEM disciplines. 4. **Science**: Researchers use FDM to prototype equipment for scientific experiments, build custom laboratory tools, and create models for visualization and testing purposes. It facilitates rapid iteration and customization in scientific endeavors. 5. **Automotive**: Automotive manufacturers employ FDM for prototyping vehicle components, tooling for assembly lines, and customized parts. It speeds up the design validation process and enhances efficiency in automotive engineering. 6. **Consumer Electronics**: FDM is utilized in consumer electronics for designing and prototyping product enclosures, casings, and internal components. It enables rapid iteration and customization to meet evolving consumer demands. 7. **Robotics**: Robotics engineers leverage FDM to prototype robot parts, create lightweight and durable components, and customize robot designs for specific applications. It supports innovation and optimization in robotic systems. 8. **Aerospace**: In aerospace, FDM is used to manufacture lightweight parts, complex geometries, and prototypes of aircraft components. It contributes to cost reduction, faster production cycles, and weight savings in aerospace engineering. 9. **Architecture**: Architects utilize FDM for creating detailed architectural models, prototypes of building components, and intricate designs. It aids in visualizing concepts, testing structural integrity, and communicating design ideas effectively. Each industry example demonstrates how FDM enhances innovation, accelerates product development, and addresses specific challenges through advanced manufacturing capabilities.

fdmffffused deposition modeling
S OL I D

SRP OCP LSP ISP DIP
OCP
OCP
  Open
  Closed
  Principle
OCP
  Open
  Closed
  Principle


              You should be able
              to extend a classes
              behavior, without
              modifying it.

Recommended for you

Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time

Is your patent a vanity piece of paper for your office wall? Or is it a reliable, defendable, assertable, property right? The difference is often quality. Is your patent simply a transactional cost and a large pile of legal bills for your startup? Or is it a leverageable asset worthy of attracting precious investment dollars, worth its cost in multiples of valuation? The difference is often quality. Is your patent application only good enough to get through the examination process? Or has it been crafted to stand the tests of time and varied audiences if you later need to assert that document against an infringer, find yourself litigating with it in an Article 3 Court at the hands of a judge and jury, God forbid, end up having to defend its validity at the PTAB, or even needing to use it to block pirated imports at the International Trade Commission? The difference is often quality. Quality will be our focus for a good chunk of the remainder of this season. What goes into a quality patent, and where possible, how do you get it without breaking the bank? ** Episode Overview ** In this first episode of our quality series, Kristen Hansen and the panel discuss: ⦿ What do we mean when we say patent quality? ⦿ Why is patent quality important? ⦿ How to balance quality and budget ⦿ The importance of searching, continuations, and draftsperson domain expertise ⦿ Very practical tips, tricks, examples, and Kristen’s Musts for drafting quality applications https://www.aurorapatents.com/patently-strategic-podcast.html

patentspatent applicationpatent prosecution
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024

This is a powerpoint that features Microsoft Teams Devices and everything that is new including updates to its software and devices for May 2024

microsoft teamsmicrosoft
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf

To help you choose the best DiskWarrior alternative, we've compiled a comparison table summarizing the features, pros, cons, and pricing of six alternatives.

data recoverydatadiskwarrior
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails

Recommended for you

Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy

Not so much to say

From the Google
  AI Challenge
   (Tronbot)
def makemove(map)
                                     From the Google
  x, y = map.my_position
  # calculate a move ...               AI Challenge
  if(valid_moves.size == 0)
    map.make_move( :NORTH )
                                        (Tronbot)
  else
    # choose move ...
    puts move # debug (like in the old days)
    map.make_move( move )
  end
end

class Map
  ...
  def make_move(direction)
    $stdout << ({:NORTH=>1, :SOUTH=>3, :EAST=>2, :WEST=>4}[direction])
    $stdout << "n"
    $stdout.flush
  end
end
def makemove(map)
                                     From the Google
  x, y = map.my_position
  # calculate a move ...               AI Challenge
  if(valid_moves.size == 0)
    map.make_move( :NORTH )
                                        (Tronbot)
  else
    # choose move ...
    puts move # debug (like in the old days)
    map.make_move( move )
  end
end

class Map
  ...
  def make_move(direction)
    $stdout << ({:NORTH=>1, :SOUTH=>3, :EAST=>2, :WEST=>4}[direction])
    $stdout << "n"
    $stdout.flush
  end
end
def makemove(map)
                                     From the Google
  x, y = map.my_position
  # calculate a move ...               AI Challenge
  if(valid_moves.size == 0)
    map.make_move( :NORTH )
                                        (Tronbot)
  else
    # choose move ...
    puts move # debug (like in the old days)
    map.make_move( move )
  end
end

class Map
  ...
  def make_move(direction)
    $stdout << ({:NORTH=>1, :SOUTH=>3, :EAST=>2, :WEST=>4}[direction])
    $stdout << "n"
    $stdout.flush
  end
end

Recommended for you

From the Google AI Challenge (Tronbot)
From the Google AI Challenge (Tronbot)
def puts(*args)
  $stderr.puts *args
end

def p(*args)
  args.map!{|arg| arg.inspect}
  puts args
end

def print(*args)
  $stderr.print *args
end
Design Sketch
SOLID Ruby, SOLID Rails

Recommended for you

class Outputter

  def initialize(io = $stderr)
    @io = io
  end

  def puts(*args)
    @io.puts *args
  end

  ...
end

out = Outputter.new
out.puts "Testing"
S OL I D

SRP OCP LSP ISP DIP
LSP
LSP
      Liskov
      Substitution
      Principle

Recommended for you

LSP
      Liskov
      Substitution
      Principle


                     Derived classes
                     must be substitutable
                     for their base
                     classes.
No Problem
  in Ruby

        Or so it seems...
No Interface...

            no problem?
Wrong !

Recommended for you

The classic violation
A square is a rectangle
Rectangle

setX
setY




        Square

setX
setY
Rectangle

Recommended for you

Rectangle
>>   class Rectangle
>>     attr_accessor :width, :height
>>   end
=>   nil
>>
?>   shape = Rectangle.new
=>   #<Rectangle:0x10114fad0>
>>   shape.width
=>   nil
>>   shape.width=3
>>   shape.width
=>   3
>>   shape.height=5
>>   shape.height
=>   5
>>   shape.width
=>   3
Square

    ?> shape = Square.new
    => #<Square:0x101107e88>
    ?> puts shape.width
    nil
    ?> shape.width=3
    => 3
    ?> shape.width
    => 3
    ?> shape.height
    => 3
Square
>> class Square
?>   def width
>>     @dimension
                            ?> shape = Square.new
>>   end
                            => #<Square:0x101107e88>
?>   def height
                            ?> puts shape.width
>>     @dimension
                            nil
>>   end
                            ?> shape.width=3
?>   def width= n
                            => 3
>>     @dimension = n
                            ?> shape.width
>>   end
                            => 3
?>   def height= n
                            ?> shape.height
>>     @dimension = n
                            => 3
>>   end
>> end
A Problem...



     Text

Recommended for you

A Problem...
>> s = [Rectangle.new, Square.new]
=> [#<Rectangle:0x1005642e8>, #<Square:0x100564298>]
>> a_rectangle = s[rand(2)]




                             Text
A Problem...
>>   s = [Rectangle.new, Square.new]
=>   [#<Rectangle:0x1005642e8>, #<Square:0x100564298>]
>>   a_rectangle = s[rand(2)]
=>   #<Square:0x100564298>
>>   a_rectangle.height=1
=>   1
>>   a_rectangle.width=3
=>   3
                                Text
>>   a_rectangle.height
A Problem...
>>   s = [Rectangle.new, Square.new]
=>   [#<Rectangle:0x1005642e8>, #<Square:0x100564298>]
>>   a_rectangle = s[rand(2)]
=>   #<Square:0x100564298>
>>   a_rectangle.height=1
=>   1
>>   a_rectangle.width=3
=>   3
                                Text
>>   a_rectangle.height
=>   3
CCD Common Conceptual
     Denominator

Recommended for you

dup
http://blog.objectmentor.com/articles/2007/02/17/
liskov-substitution-principle-and-the-ruby-core-libraries
irb 1:0> 5.respond_to? :dup




          http://blog.objectmentor.com/articles/2007/02/17/
          liskov-substitution-principle-and-the-ruby-core-libraries
irb 1:0> 5.respond_to? :dup
=> true




          http://blog.objectmentor.com/articles/2007/02/17/
          liskov-substitution-principle-and-the-ruby-core-libraries

Recommended for you

irb 1:0> 5.respond_to? :dup
=> true
irb 2:0> 5.dup




          http://blog.objectmentor.com/articles/2007/02/17/
          liskov-substitution-principle-and-the-ruby-core-libraries
irb 1:0> 5.respond_to? :dup
=> true
irb 2:0> 5.dup
TypeError: can't dup Fixnum
        from (irb):1:in `dup'
        from (irb):1
irb 3:0>




          http://blog.objectmentor.com/articles/2007/02/17/
          liskov-substitution-principle-and-the-ruby-core-libraries
S OL I D

SRP OCP LSP ISP DIP
ISP

Recommended for you

ISP
      Interface
      Segregation
      Principle
ISP
      Interface
      Segregation
      Principle


                    Make fine grained
                    interfaces that are
                    client specific.
SOLID Ruby, SOLID Rails
Users Controller

Recommended for you

Users Controller
class UsersController < ApplicationController

  ssl_required :new, :create, :edit, :update, :destroy, :activate,
:change_passwort, :forgot_password, :reset_password, :make_profile,
:my_contacts
  ssl_allowed :eula, :index, :show

  access_control
[:suspend, :unsuspend, :destroy, :purge, :delete, :admin, :ban, :remove_ban] =>
'admin'

 before_filter :find_user

 skip_after_filter :store_location

  def show
    unless @user == current_user
      redirect_to access_denied_path(@locale)
    else
      respond_to do |format|
        format.html
        format.js { render :partial => "users/#{@context.title}/#{@partial}" }
      end
    end
  end
...
more UsersController
more UsersController
def activate
  logout_keeping_session!
  user = User.find_by_activation_code(params[:activation_code]) unless
                          params[:activation_code].blank?

  case
  when (!params[:activation_code].blank?) && user && !user.active?
    user.activate!
    flash[:notice] = t(:message_sign_up_complete)
    unless params[:context].blank?
      redirect_to login_path(:context => params[:context])
    else
      redirect_to "/login"
    end
  when params[:activation_code].blank?
    flash[:error] = t(:message_activation_code_missing)
    redirect_back_or_default("/")
  else
    flash[:error] = t(:message_user_with_that_activation_code_missing)
    redirect_back_or_default("/")
  end
end
User Class Revisited

Recommended for you

User Class Revisited
class User < ActiveRecord::Base
  ...
end



class Registration < ActiveRecord::Base
   set_table_name "users"

   acts_as_state_machine :initial => :pending

   state :pending, :enter => :make_activation_code
   state :active, :enter => :do_activate
   ...

   event :activate do
     transitions :from => :pending, :to => :active
   end
   ...
end
SOLID Ruby, SOLID Rails
class RegistrationController < ApplicationController
  ...
  def activate
    logout_keeping_session!
    code_is_blank = params[:activation_code].blank?
    registration =
Registration.find_by_activation_code(params[:activation_code]) unless
code_is_blank

   case
   when (!code_is_blank) && registration && !registratio.active?
     registration.activate!
     flash[:notice] = t(:message_sign_up_complete)
     unless params[:context].blank?
       redirect_to login_path(:context => params[:context])
     else
       redirect_to "/login"
     end
   when code_is_blank
     flash[:error] = t(:message_activation_code_missing)
     redirect_back_or_default("/")
   else
     flash[:error] = t(:message_user_with_that_activation_code_missing)
     redirect_back_or_default("/")
   end
 end
 ...
S OL I D

SRP OCP LSP ISP DIP

Recommended for you

DIP
DIP
      Dependency
      Inversion
      Principle
DIP
      Dependency
      Inversion
      Principle


                   Depend on
                   abstractions, not on
                   concretions.
SOLID Ruby, SOLID Rails

Recommended for you

From our OCP example to DIP
From our OCP example to DIP



out = Outputter.new
out.puts "Testing"
The code we wish we had
The code we wish we had
class TronBot
  def initialize
    @@out = TRON_ENVIRONMENT[:debugger]
  end

  def some_method
    ...
    @@out.puts "Testing"
    ...
  end

end

Recommended for you

TSTTCPW
TSTTCPW


TRON_ENVIRONMENT = {
        :debugger => Outputter.new ($stderr),
        :game_engine => Outputter.new ($stdout),
        :user_io => Outputter.new ($stderr)
        }
Later...
Later...


TRON_ENVIRONMENT = {
        :debugger => Outputter.new ($stderr),
        :game_engine => Outputter.new (TCP_OUTPUTTER),
        :user_io => Outputter.new ($stderr)
        }

Recommended for you

DIP Violation in Controller
DIP Violation in Controller
format.js do
  render :update do |page|
    if @parent_object.class == EspGoal
      @esp_goal_descriptor = @current_object
      page.replace_html "descriptor_#{@current_object.id}",
          :partial => "edit_esp_goal_descriptor",
          :locals => {:esp_goal_descriptor => @esp_goal_descriptor,
                      :parent_object => @parent_object}
    else
      @goal_descriptor = @current_object
      page.replace_html "descriptor_#{@current_object.id}",
          :partial => "edit_goal_descriptor",
          :locals => {:goal_descriptor => @goal_descriptor,
                      :parent_object => @parent_object}
    end
  end
end
DIP Violation in Controller
DIP Violation in Controller
format.js do
  render :update do |page|
    if @parent_object.class == EspGoal
      @esp_goal_descriptor = @current_object
      page.replace_html "descriptor_#{@current_object.id}",
          :partial => "edit_esp_goal_descriptor",
          :locals => {:esp_goal_descriptor => @esp_goal_descriptor,
                      :parent_object => @parent_object}
    else if @parent_object.class == Goal
      @goal_descriptor = @current_object
      page.replace_html "descriptor_#{@current_object.id}",
          :partial => "edit_goal_descriptor",
          :locals => {:goal_descriptor => @goal_descriptor,
                      :parent_object => @parent_object}
    else if @parent_object.class == LearningGoal
      ...
      ...
    end
  end
end

Recommended for you

SOLID Ruby, SOLID Rails
1st Refactoring
1st Refactoring
def show
  ...
  format.js do
    render :update do |page|
      page.replace_html "descriptor_#{@current_object.id}",
                        @parent_object.page_replacement(@current_object)
    end
  end
end

class EspGoal
  def page_replacement child
     { :partial => "edit_esp_goal_descriptor",
       :locals => {:esp_goal_descriptor => child,
                   :parent_object => self}
     }
  end
end

class Goal
  def page_replacement child
    { :partial => "edit_goal_descriptor",
      :locals => {:goal_descriptor => child,
                  :parent_object => self}
    }
  end
end
SOLID Ruby, SOLID Rails

Recommended for you

2nd Refactoring
(Behaviour)
class EspGoalReplacmenent
                                             2nd Refactoring
  def self.my_class_sym

  end
      EspGoal.to_sym                         (Behaviour)
  def partial_definition child
  { :partial => "edit_esp_goal_descriptor",
       :locals => {:esp_goal_descriptor => child,
                   :parent_object => child.esp_goal}
    }
  end
end

class GoalReplacmenent
  def self.my_class_sym
      Goal.to_sym
  end
  def partial_definition child
  { :partial => "edit_goal_descriptor",
       :locals => {:goal_descriptor => child,
                   :parent_object => child.goal}
    }
  end
end
2nd Refactoring
(wiring)
2nd Refactoring
                                             (wiring)
class PartialContainer
  def add class_symbol, partial_replacement
    @@partinal_replacements.add( class_symbol => partial_replacement)
  end

  def self.partial_replacement an_object
    unless @@partial_replacments
      self.add( EspGoalReplacement.my_class_sym, EspGoalReplacment.new)
      self.add( GoalReplacement.my_class_sym, GoalReplacment.new)
    end
    @@partial_replacement[an_object.class]
  end
end

Recommended for you

DIP Violation in Controller
DIP Violation in Controller
format.js do
  render :update do |page|
    if @parent_object.class == EspGoal
      @esp_goal_descriptor = @current_object
      page.replace_html "descriptor_#{@current_object.id}",
:partial => "edit_esp_goal_descriptor",
          :locals => {:esp_goal_descriptor => @esp_goal_descriptor,
                      :parent_object => @parent_object}
    else
      @goal_descriptor = @current_object
      page.replace_html "descriptor_#{@current_object.id}",
:partial => "edit_goal_descriptor",
          :locals => {:goal_descriptor => @goal_descriptor,
          :parent_object => @parent_object}
    end
  end
end
2nd Refactoring
- the Controller -
2nd Refactoring
                   - the Controller -
def show
  ...
  format.js do
    render :update do |page|
      page.replace_html "descriptor_#{@current_object.id}",
                        PartialContainer.partial_replacement(@parent_object).
                                         partial_definition(@current_object)
    end
  end
end

Recommended for you

SOLID Ruby, SOLID Rails
SOLID
SOLID

SRP OCP LSP ISP DIP
SRP OCP LSP ISP DIP

Recommended for you

S OL ID

SRP OCP LSP ISP DIP
S OL ID

SRP OCP LSP ISP DIP
S OL ID

SRP OCP LSP ISP DIP
S OL ID

SRP OCP LSP ISP DIP

Recommended for you

S OL ID

SRP OCP LSP ISP DIP
S O L I D Questions?


SRP OCP LSP ISP DIP
Domo Arigato
Coding Dojo
           Wednesday 11:10
              Salon 3
The Way of the carpenter is to
become proficient in the use of
his tools, first to lay his plans with a
true measure and then perform his
work according to plan.

                   – Go Rin No Sho

Recommended for you

Credits (1/2)
PPP-Article (online)
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

Photos
http://www.flickr.com/photos/dieterkarner/370967891/
http://www.flickr.com/photos/popcorncx/2221630487/sizes/l/
http://www.flickr.com/photos/bdesham/2432400623/
http://www.flickr.com/photos/popcorncx/2221630487/
http://www.flickr.com/photos/glennbatuyong/4081599002/in/photostream/
http://www.flickr.com/photos/glennbatuyong/4081599168/in/photostream/
http://www.flickr.com/photos/renfield/3865907619/


                                                                        91
Credits (2/2)
Photos
http://www.flickr.com/photos/renfield/3865907619/
http://www.flickr.com/photos/maxpower/5160699/
http://programmer.97things.oreilly.com/wiki/index.php/Uncle_Bob
http://www.flickr.com/photos/georgivar/3288942086/
http://www.everystockphoto.com/photo.php?imageId=237523
http://www.flickr.com/photos/pasukaru76/3992935923/




                                                                  92
Lizense


http://creativecommons.org/licenses/by-sa/
  3.0/de/




                                         93
Jens-Christian Fischer        Michael Mahlberg

InVisible GmbH                Consulting Guild AG



@jcfischer                     @MMahlberg

jens-christian@invisible.ch   mm@michaelmahlberg.de

http://blog.invisible.ch      http://agile-aspects.blogspot.com




                                                             94

Recommended for you

Get the Presentation
http://github.com/MichaelMahlberg/RailsWayCon2010




                                                    95
96

More Related Content

Similar to SOLID Ruby, SOLID Rails

Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Coupa Software
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Jon Kruger
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
Giordano Scalzo
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
Mohit Jain
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
Rabble .
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
Brian Hogan
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code
Wim Godden
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
Movel
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
pauldix
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
pauldix
 
Rails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not KnowRails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not Know
Chris Oliver
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
shaokun
 
Beyond php it's not (just) about the code
Beyond php   it's not (just) about the codeBeyond php   it's not (just) about the code
Beyond php it's not (just) about the code
Wim Godden
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Rabble .
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
Jay Shirley
 
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Joao Lucas Santana
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
Jonathan Felch
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
Mike Subelsky
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
Plataformatec
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
bryanbibat
 

Similar to SOLID Ruby, SOLID Rails (20)

Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Rails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not KnowRails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not Know
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Beyond php it's not (just) about the code
Beyond php   it's not (just) about the codeBeyond php   it's not (just) about the code
Beyond php it's not (just) about the code
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 

More from Jens-Christian Fischer

Beyond HTML Internet Briefing
Beyond HTML Internet BriefingBeyond HTML Internet Briefing
Beyond HTML Internet Briefing
Jens-Christian Fischer
 
Beyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehr
Beyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehrBeyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehr
Beyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehr
Jens-Christian Fischer
 
Architektur der kleinen Bausteine
Architektur der kleinen BausteineArchitektur der kleinen Bausteine
Architektur der kleinen Bausteine
Jens-Christian Fischer
 
Taking your Web App for a walk
Taking your Web App for a walkTaking your Web App for a walk
Taking your Web App for a walk
Jens-Christian Fischer
 
Mobino at Webmondy Frankfurt, Mai 2011
Mobino at Webmondy Frankfurt, Mai 2011Mobino at Webmondy Frankfurt, Mai 2011
Mobino at Webmondy Frankfurt, Mai 2011
Jens-Christian Fischer
 
Testing distributed, complex web applications
Testing distributed, complex web applicationsTesting distributed, complex web applications
Testing distributed, complex web applications
Jens-Christian Fischer
 
Ruby Coding Dojo
Ruby Coding DojoRuby Coding Dojo
Ruby Coding Dojo
Jens-Christian Fischer
 
Synology Workshop07 06
Synology Workshop07 06Synology Workshop07 06
Synology Workshop07 06
Jens-Christian Fischer
 
Offline Arbeiten
Offline ArbeitenOffline Arbeiten
Offline Arbeiten
Jens-Christian Fischer
 

More from Jens-Christian Fischer (9)

Beyond HTML Internet Briefing
Beyond HTML Internet BriefingBeyond HTML Internet Briefing
Beyond HTML Internet Briefing
 
Beyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehr
Beyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehrBeyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehr
Beyond HTML - Scriptsprachen, Frameworks, Templatesprachen und vieles mehr
 
Architektur der kleinen Bausteine
Architektur der kleinen BausteineArchitektur der kleinen Bausteine
Architektur der kleinen Bausteine
 
Taking your Web App for a walk
Taking your Web App for a walkTaking your Web App for a walk
Taking your Web App for a walk
 
Mobino at Webmondy Frankfurt, Mai 2011
Mobino at Webmondy Frankfurt, Mai 2011Mobino at Webmondy Frankfurt, Mai 2011
Mobino at Webmondy Frankfurt, Mai 2011
 
Testing distributed, complex web applications
Testing distributed, complex web applicationsTesting distributed, complex web applications
Testing distributed, complex web applications
 
Ruby Coding Dojo
Ruby Coding DojoRuby Coding Dojo
Ruby Coding Dojo
 
Synology Workshop07 06
Synology Workshop07 06Synology Workshop07 06
Synology Workshop07 06
 
Offline Arbeiten
Offline ArbeitenOffline Arbeiten
Offline Arbeiten
 

Recently uploaded

Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
welrejdoall
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
jackson110191
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
ArgaBisma
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Mydbops
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
Lidia A.
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
Stephanie Beckett
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
Larry Smarr
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Bert Blevins
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
rajancomputerfbd
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
Stephanie Beckett
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
RaminGhanbari2
 

Recently uploaded (20)

Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
 

SOLID Ruby, SOLID Rails

  • 1. Michael Mahlberg, Consulting Guild AG Jens-Christian Fischer, InVisible GmbH SOLID Ruby - SOLID Rails Establishing a sustainable codebase
  • 2. Who? Michael Mahlberg
  • 3. Founder of roughly a dozen companies over the last two decades
  • 6. Working as A consultant on software processes, architecture & design for > 2 decades
  • 8. >> relevance != nil => true
  • 9. Who? Jens-Christian Fischer
  • 10. Tinkerer, Practician, Author and generally interested in way too many things
  • 12. SOLID is not a Law
  • 13. PPP (by Robert C. Martin) Agile Software Development, Principles, Patterns, and Practices
  • 14. Principles! You know - more like guidelines
  • 15. SOLID
  • 16. SOLID SRP OCP L S O LSP I ISP DIP D
  • 17. S OL I D SRP OCP LSP ISP DIP
  • 18. SRP
  • 19. SRP Single Responsibility Principle
  • 20. SRP Single Responsibility Principle A class should have one, and only one, reason to change.
  • 21. User Class require 'digest/sha1' class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken #TODO Check login redirect if this filter is skipped #skip_after_filter :store_location # Virtual attribute for the unencrypted password attr_accessor :password belongs_to :country has_one :user_profile, :dependent => :destroy has_one :note has_many :queries has_many :tags, :foreign_key => "created_by" has_many :taggings, :as => :tagger has_many :organizations, :through => :affiliations has_many :affiliations has_many :locations, :through => :affiliations has_many :projects, :through => :memberships has_many :memberships has_many :public_assets, :through => :privileges has_many :descriptions, :through => :privileges has_many :assessments, :through => :privileges has_many :description_profiles, :through => :privileges has_many :privileges has_many :diaries has_many :roles, :through => :commitments has_many :commitments has_many :activities has_many :messages has_many :fellowships
  • 22. end def editable_by?(user=nil) self.created_by == user end def readable_by?(user=nil) self.created_by == user end def boards User Class Board.all :conditions => { :user_group_id => self.user_groups.collect{ |g| g.id }} end def discussions Discussion.all :conditions => { :board_id => self.boards.collect{ |b| b.id }} end def organization_roles role_ids = Affiliation.all(:conditions => {:user_id => self.id}).collect{|a| a.role_id}.uniq roles = Role.find(role_ids) end def user_group_roles role_ids = Fellowship.all(:conditions => {:user_id => self.id}).collect{|a| a.role_id}.uniq roles = Role.find(role_ids) end def project_roles role_ids = Membership.all(:conditions => {:user_id => self.id}).collect{|a| a.role_id}.uniq roles = Role.find(role_ids) end def all_roles roles = (self.organization_roles + self.user_group_roles + self.project_roles).uniq end def tags_of(user) taggings = Tagging.all :conditions => {:taggable_type => "User", :taggable_id => self.id, :tagger_type => "User", :tagge tags = taggings.collect {|t| t.tag.name}.uniq.sort end
  • 23. So what‘s wrong with this?
  • 25. From: user.rb class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken ... belongs_to :country ... has_one :user_profile, :dependent => :destroy has_many :queries has_many :tags, :foreign_key => "created_by" ... validates_presence_of :login, :email, :country_id validates_presence_of :password, :if => :password_required? ...
  • 27. From: user.rb acts_as_state_machine :initial => :pending state :pending, :enter => :make_activation_code state :active, :enter => :do_activate ... event :register do transitions :from => :passive, :to => :pending, :guard => Proc.new {|u| !(u.crypted_password.blank? && u.password.blank?) } end ... def message_threads self.message_threads + self.message_threads end
  • 29. From: user.rb def forum_nickname self.user_profile.nickname.blank? ? "#{self.first_name} #{self.last_name}" : self.user_profile.nickname end def name "#{self.first_name} #{self.last_name}" rescue 'n/a' end def email_with_name "#{self.first_name} #{self.last_name} <#{self.email}>" end
  • 31. From: user.rb def is_admin? self.roles.collect{|role| role.title}.include?('admin') end def countries [self.country] end
  • 33. From: user.rb def boards Board.all :conditions => { :user_group_id => self.user_groups.collect{ |g| g.id }} end def discussions Discussion.all :conditions => { :board_id => self.boards.collect{ |b| b.id }} end def organization_roles role_ids = Affiliation.all(:conditions => {:user_id => self.id}).collect{|a| a.role_id}.uniq roles = Role.find(role_ids) end
  • 35. From: user.rb def make_password_reset_code self.password_reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end def self.published_users User.all(:conditions => ['state = ?', 'published'], :order => 'login ASC', :include => [:user_profile]) end
  • 36. Anyone notice a pattern?
  • 39. Authentication Roles Mailers State ...
  • 40. So how? Mixins
  • 42. New User Model class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken include Project::UserStates include Project::UserMailer include Project::UserForum include Project::UserMessages ... end
  • 44. UserMessages module Project module UserMessages # to be included in User Model has_many :messages def message_threads MessageThread.all(:conditions => ["sender_id = ? or receiver_id = ?", self.id, self.id]) end end end
  • 47. def transfer(data, url) h = Net::HTTP.new(self.uri.host, self.uri.port) RAILS_DEFAULT_LOGGER.debug "connecting to CL: #{self.uri}" RAILS_DEFAULT_LOGGER.debug "connecting to CL: #{url}" resp = h.post(url, data, {'Content-Type' => 'application/xml'}) response_code = resp.code.to_i location = if response_code == 201 resp['Location'] else RAILS_DEFAULT_LOGGER.debug "error from CL: #{response_code}" RAILS_DEFAULT_LOGGER.debug "error from CL: #{resp.body}" @error = resp.body nil end [response_code, location] end
  • 49. def transfer(data, document) if document.cl_document_url != nil self.uri = URI.parse(document.cl_document_url ) h = Net::HTTP.new(self.uri.host, self.uri.port) response = h.post(self.uri, data, {'Content-Type' => 'application/xml'}) else h = Net::HTTP.new(self.uri.host, self.uri.port) response = h.post("/tasks", data, {'Content-Type' => 'application/xml'}) end response_code = response.code.to_i if response_code == 201 location = response['Location'] document.cl_document_url = location document.save! else nil end [response_code, location] end
  • 50. def transfer(data, document) if document.cl_document_url != nil self.uri = URI.parse(document.cl_document_url ) h = Net::HTTP.new(self.uri.host, self.uri.port) response = h.post(self.uri, data, {'Content-Type' => 'application/xml'}) else h = Net::HTTP.new(self.uri.host, self.uri.port) response = h.post("/tasks", data, {'Content-Type' => 'application/xml'}) end response_code = response.code.to_i if response_code == 201 location = response['Location'] document.cl_document_url = location document.save! else nil end [response_code, location] end
  • 52. SRP Transfer def transfer data open_connection post data return location end def open_connection @http = Net::HTTP.new(self.uri.host, self.uri.port) end def post data @response = http.post(self.url, data, {'Content-Type' => 'application/xml'}) end
  • 54. def location get_location if created? # returns nil if not created? end def response_code @response.code.to_i end def created? response_code == 201 end def get_location @response['Location'] end def error @response.body end
  • 55. Add a 16-band equalizer & a BlueRay® player to this...
  • 56. And now to this...
  • 57. S OL I D SRP OCP LSP ISP DIP
  • 58. OCP
  • 59. OCP Open Closed Principle
  • 60. OCP Open Closed Principle You should be able to extend a classes behavior, without modifying it.
  • 65. From the Google AI Challenge (Tronbot)
  • 66. def makemove(map) From the Google x, y = map.my_position # calculate a move ... AI Challenge if(valid_moves.size == 0) map.make_move( :NORTH ) (Tronbot) else # choose move ... puts move # debug (like in the old days) map.make_move( move ) end end class Map ... def make_move(direction) $stdout << ({:NORTH=>1, :SOUTH=>3, :EAST=>2, :WEST=>4}[direction]) $stdout << "n" $stdout.flush end end
  • 67. def makemove(map) From the Google x, y = map.my_position # calculate a move ... AI Challenge if(valid_moves.size == 0) map.make_move( :NORTH ) (Tronbot) else # choose move ... puts move # debug (like in the old days) map.make_move( move ) end end class Map ... def make_move(direction) $stdout << ({:NORTH=>1, :SOUTH=>3, :EAST=>2, :WEST=>4}[direction]) $stdout << "n" $stdout.flush end end
  • 68. def makemove(map) From the Google x, y = map.my_position # calculate a move ... AI Challenge if(valid_moves.size == 0) map.make_move( :NORTH ) (Tronbot) else # choose move ... puts move # debug (like in the old days) map.make_move( move ) end end class Map ... def make_move(direction) $stdout << ({:NORTH=>1, :SOUTH=>3, :EAST=>2, :WEST=>4}[direction]) $stdout << "n" $stdout.flush end end
  • 69. From the Google AI Challenge (Tronbot)
  • 70. From the Google AI Challenge (Tronbot) def puts(*args) $stderr.puts *args end def p(*args) args.map!{|arg| arg.inspect} puts args end def print(*args) $stderr.print *args end
  • 73. class Outputter def initialize(io = $stderr) @io = io end def puts(*args) @io.puts *args end ... end out = Outputter.new out.puts "Testing"
  • 74. S OL I D SRP OCP LSP ISP DIP
  • 75. LSP
  • 76. LSP Liskov Substitution Principle
  • 77. LSP Liskov Substitution Principle Derived classes must be substitutable for their base classes.
  • 78. No Problem in Ruby Or so it seems...
  • 79. No Interface... no problem?
  • 82. A square is a rectangle
  • 83. Rectangle setX setY Square setX setY
  • 85. Rectangle >> class Rectangle >> attr_accessor :width, :height >> end => nil >> ?> shape = Rectangle.new => #<Rectangle:0x10114fad0> >> shape.width => nil >> shape.width=3 >> shape.width => 3 >> shape.height=5 >> shape.height => 5 >> shape.width => 3
  • 86. Square ?> shape = Square.new => #<Square:0x101107e88> ?> puts shape.width nil ?> shape.width=3 => 3 ?> shape.width => 3 ?> shape.height => 3
  • 87. Square >> class Square ?> def width >> @dimension ?> shape = Square.new >> end => #<Square:0x101107e88> ?> def height ?> puts shape.width >> @dimension nil >> end ?> shape.width=3 ?> def width= n => 3 >> @dimension = n ?> shape.width >> end => 3 ?> def height= n ?> shape.height >> @dimension = n => 3 >> end >> end
  • 88. A Problem... Text
  • 89. A Problem... >> s = [Rectangle.new, Square.new] => [#<Rectangle:0x1005642e8>, #<Square:0x100564298>] >> a_rectangle = s[rand(2)] Text
  • 90. A Problem... >> s = [Rectangle.new, Square.new] => [#<Rectangle:0x1005642e8>, #<Square:0x100564298>] >> a_rectangle = s[rand(2)] => #<Square:0x100564298> >> a_rectangle.height=1 => 1 >> a_rectangle.width=3 => 3 Text >> a_rectangle.height
  • 91. A Problem... >> s = [Rectangle.new, Square.new] => [#<Rectangle:0x1005642e8>, #<Square:0x100564298>] >> a_rectangle = s[rand(2)] => #<Square:0x100564298> >> a_rectangle.height=1 => 1 >> a_rectangle.width=3 => 3 Text >> a_rectangle.height => 3
  • 92. CCD Common Conceptual Denominator
  • 93. dup
  • 95. irb 1:0> 5.respond_to? :dup http://blog.objectmentor.com/articles/2007/02/17/ liskov-substitution-principle-and-the-ruby-core-libraries
  • 96. irb 1:0> 5.respond_to? :dup => true http://blog.objectmentor.com/articles/2007/02/17/ liskov-substitution-principle-and-the-ruby-core-libraries
  • 97. irb 1:0> 5.respond_to? :dup => true irb 2:0> 5.dup http://blog.objectmentor.com/articles/2007/02/17/ liskov-substitution-principle-and-the-ruby-core-libraries
  • 98. irb 1:0> 5.respond_to? :dup => true irb 2:0> 5.dup TypeError: can't dup Fixnum from (irb):1:in `dup' from (irb):1 irb 3:0> http://blog.objectmentor.com/articles/2007/02/17/ liskov-substitution-principle-and-the-ruby-core-libraries
  • 99. S OL I D SRP OCP LSP ISP DIP
  • 100. ISP
  • 101. ISP Interface Segregation Principle
  • 102. ISP Interface Segregation Principle Make fine grained interfaces that are client specific.
  • 105. Users Controller class UsersController < ApplicationController ssl_required :new, :create, :edit, :update, :destroy, :activate, :change_passwort, :forgot_password, :reset_password, :make_profile, :my_contacts ssl_allowed :eula, :index, :show access_control [:suspend, :unsuspend, :destroy, :purge, :delete, :admin, :ban, :remove_ban] => 'admin' before_filter :find_user skip_after_filter :store_location def show unless @user == current_user redirect_to access_denied_path(@locale) else respond_to do |format| format.html format.js { render :partial => "users/#{@context.title}/#{@partial}" } end end end ...
  • 107. more UsersController def activate logout_keeping_session! user = User.find_by_activation_code(params[:activation_code]) unless params[:activation_code].blank? case when (!params[:activation_code].blank?) && user && !user.active? user.activate! flash[:notice] = t(:message_sign_up_complete) unless params[:context].blank? redirect_to login_path(:context => params[:context]) else redirect_to "/login" end when params[:activation_code].blank? flash[:error] = t(:message_activation_code_missing) redirect_back_or_default("/") else flash[:error] = t(:message_user_with_that_activation_code_missing) redirect_back_or_default("/") end end
  • 109. User Class Revisited class User < ActiveRecord::Base ... end class Registration < ActiveRecord::Base set_table_name "users" acts_as_state_machine :initial => :pending state :pending, :enter => :make_activation_code state :active, :enter => :do_activate ... event :activate do transitions :from => :pending, :to => :active end ... end
  • 111. class RegistrationController < ApplicationController ... def activate logout_keeping_session! code_is_blank = params[:activation_code].blank? registration = Registration.find_by_activation_code(params[:activation_code]) unless code_is_blank case when (!code_is_blank) && registration && !registratio.active? registration.activate! flash[:notice] = t(:message_sign_up_complete) unless params[:context].blank? redirect_to login_path(:context => params[:context]) else redirect_to "/login" end when code_is_blank flash[:error] = t(:message_activation_code_missing) redirect_back_or_default("/") else flash[:error] = t(:message_user_with_that_activation_code_missing) redirect_back_or_default("/") end end ...
  • 112. S OL I D SRP OCP LSP ISP DIP
  • 113. DIP
  • 114. DIP Dependency Inversion Principle
  • 115. DIP Dependency Inversion Principle Depend on abstractions, not on concretions.
  • 117. From our OCP example to DIP
  • 118. From our OCP example to DIP out = Outputter.new out.puts "Testing"
  • 119. The code we wish we had
  • 120. The code we wish we had class TronBot def initialize @@out = TRON_ENVIRONMENT[:debugger] end def some_method ... @@out.puts "Testing" ... end end
  • 122. TSTTCPW TRON_ENVIRONMENT = { :debugger => Outputter.new ($stderr), :game_engine => Outputter.new ($stdout), :user_io => Outputter.new ($stderr) }
  • 124. Later... TRON_ENVIRONMENT = { :debugger => Outputter.new ($stderr), :game_engine => Outputter.new (TCP_OUTPUTTER), :user_io => Outputter.new ($stderr) }
  • 125. DIP Violation in Controller
  • 126. DIP Violation in Controller format.js do render :update do |page| if @parent_object.class == EspGoal @esp_goal_descriptor = @current_object page.replace_html "descriptor_#{@current_object.id}", :partial => "edit_esp_goal_descriptor", :locals => {:esp_goal_descriptor => @esp_goal_descriptor, :parent_object => @parent_object} else @goal_descriptor = @current_object page.replace_html "descriptor_#{@current_object.id}", :partial => "edit_goal_descriptor", :locals => {:goal_descriptor => @goal_descriptor, :parent_object => @parent_object} end end end
  • 127. DIP Violation in Controller
  • 128. DIP Violation in Controller format.js do render :update do |page| if @parent_object.class == EspGoal @esp_goal_descriptor = @current_object page.replace_html "descriptor_#{@current_object.id}", :partial => "edit_esp_goal_descriptor", :locals => {:esp_goal_descriptor => @esp_goal_descriptor, :parent_object => @parent_object} else if @parent_object.class == Goal @goal_descriptor = @current_object page.replace_html "descriptor_#{@current_object.id}", :partial => "edit_goal_descriptor", :locals => {:goal_descriptor => @goal_descriptor, :parent_object => @parent_object} else if @parent_object.class == LearningGoal ... ... end end end
  • 131. 1st Refactoring def show ... format.js do render :update do |page| page.replace_html "descriptor_#{@current_object.id}", @parent_object.page_replacement(@current_object) end end end class EspGoal def page_replacement child { :partial => "edit_esp_goal_descriptor", :locals => {:esp_goal_descriptor => child, :parent_object => self} } end end class Goal def page_replacement child { :partial => "edit_goal_descriptor", :locals => {:goal_descriptor => child, :parent_object => self} } end end
  • 134. class EspGoalReplacmenent 2nd Refactoring def self.my_class_sym end EspGoal.to_sym (Behaviour) def partial_definition child { :partial => "edit_esp_goal_descriptor", :locals => {:esp_goal_descriptor => child, :parent_object => child.esp_goal} } end end class GoalReplacmenent def self.my_class_sym Goal.to_sym end def partial_definition child { :partial => "edit_goal_descriptor", :locals => {:goal_descriptor => child, :parent_object => child.goal} } end end
  • 136. 2nd Refactoring (wiring) class PartialContainer def add class_symbol, partial_replacement @@partinal_replacements.add( class_symbol => partial_replacement) end def self.partial_replacement an_object unless @@partial_replacments self.add( EspGoalReplacement.my_class_sym, EspGoalReplacment.new) self.add( GoalReplacement.my_class_sym, GoalReplacment.new) end @@partial_replacement[an_object.class] end end
  • 137. DIP Violation in Controller
  • 138. DIP Violation in Controller format.js do render :update do |page| if @parent_object.class == EspGoal @esp_goal_descriptor = @current_object page.replace_html "descriptor_#{@current_object.id}", :partial => "edit_esp_goal_descriptor", :locals => {:esp_goal_descriptor => @esp_goal_descriptor, :parent_object => @parent_object} else @goal_descriptor = @current_object page.replace_html "descriptor_#{@current_object.id}", :partial => "edit_goal_descriptor", :locals => {:goal_descriptor => @goal_descriptor, :parent_object => @parent_object} end end end
  • 139. 2nd Refactoring - the Controller -
  • 140. 2nd Refactoring - the Controller - def show ... format.js do render :update do |page| page.replace_html "descriptor_#{@current_object.id}", PartialContainer.partial_replacement(@parent_object). partial_definition(@current_object) end end end
  • 142. SOLID
  • 143. SOLID SRP OCP LSP ISP DIP
  • 144. SRP OCP LSP ISP DIP
  • 145. S OL ID SRP OCP LSP ISP DIP
  • 146. S OL ID SRP OCP LSP ISP DIP
  • 147. S OL ID SRP OCP LSP ISP DIP
  • 148. S OL ID SRP OCP LSP ISP DIP
  • 149. S OL ID SRP OCP LSP ISP DIP
  • 150. S O L I D Questions? SRP OCP LSP ISP DIP
  • 152. Coding Dojo Wednesday 11:10 Salon 3 The Way of the carpenter is to become proficient in the use of his tools, first to lay his plans with a true measure and then perform his work according to plan. – Go Rin No Sho
  • 156. Jens-Christian Fischer Michael Mahlberg InVisible GmbH Consulting Guild AG @jcfischer @MMahlberg jens-christian@invisible.ch mm@michaelmahlberg.de http://blog.invisible.ch http://agile-aspects.blogspot.com 94
  • 158. 96

Editor's Notes