The document discusses object-oriented programming in Ruby. It introduces some key concepts in OOP like classes, objects, identity, state, and behavior. It also covers Ruby-specific paradigms like modules and mixins. Some common design patterns are mentioned like singleton, iterator, and decorator. The document provides examples to illustrate concepts like inheritance, polymorphism, and visibility in modules.
This document provides an introduction to Groovy for Java developers. It discusses Groovy's features such as closures, optional typing and syntax, and how it compiles to Java bytecode. It then provides examples of writing a simple Groovy script to generate XML, using closures, mocking objects in tests, and building projects with Ant.
This document discusses Ruby on Rails extensions provided by ActiveSupport. It explains that ActiveSupport provides Ruby extensions, utility classes, and other features used across Rails. It then summarizes some common extensions, including methods added to all objects like blank?, present?, and try. The document provides code examples for how these extensions work and which ActiveSupport files define them.
Here is a Python function that calculates the distance between two points given their x and y coordinates:
```python
import math
def distance_between_points(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
```
To use it:
```python
distance = distance_between_points(1, 2, 4, 5)
print(distance)
```
This would print 3.605551275463989, which is the distance between the points (1,2) and (4,5).
The key steps are:
1.
The document discusses basic inheritance in Python. It explains that all classes inherit from the base Object class. Inheritance allows creating subclasses that inherit attributes and methods from a parent superclass. This allows code reuse and adding specialized behavior. An example creates a Contact class to store names and emails, with a Supplier subclass that adds an "order" method. A SupplierCheck subclass then overrides the order method to check the customer balance before processing orders.
This document provides an introduction to object oriented PHP by explaining key concepts like encapsulation, inheritance, polymorphism, and abstraction. It defines classes, objects, properties, methods, and constructs. Examples are provided to demonstrate how to define classes, instantiate objects, set properties, create and extend classes, implement interfaces and abstract classes, and override methods.
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
This document provides an introduction to Groovy for Java developers. It discusses Groovy's features such as closures, optional typing and syntax, and how it compiles to Java bytecode. It then provides examples of writing a simple Groovy script to generate XML, using closures, mocking objects in tests, and building projects with Ant.
This document discusses Ruby on Rails extensions provided by ActiveSupport. It explains that ActiveSupport provides Ruby extensions, utility classes, and other features used across Rails. It then summarizes some common extensions, including methods added to all objects like blank?, present?, and try. The document provides code examples for how these extensions work and which ActiveSupport files define them.
Here is a Python function that calculates the distance between two points given their x and y coordinates:
```python
import math
def distance_between_points(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
```
To use it:
```python
distance = distance_between_points(1, 2, 4, 5)
print(distance)
```
This would print 3.605551275463989, which is the distance between the points (1,2) and (4,5).
The key steps are:
1.
The document discusses basic inheritance in Python. It explains that all classes inherit from the base Object class. Inheritance allows creating subclasses that inherit attributes and methods from a parent superclass. This allows code reuse and adding specialized behavior. An example creates a Contact class to store names and emails, with a Supplier subclass that adds an "order" method. A SupplierCheck subclass then overrides the order method to check the customer balance before processing orders.
This document provides an introduction to object oriented PHP by explaining key concepts like encapsulation, inheritance, polymorphism, and abstraction. It defines classes, objects, properties, methods, and constructs. Examples are provided to demonstrate how to define classes, instantiate objects, set properties, create and extend classes, implement interfaces and abstract classes, and override methods.
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
The document discusses principles of writing clean code, including:
- Using consistent code style and formatting through style guides and linters.
- Avoiding duplicate code through principles like DRY.
- Using intention-revealing names for variables, functions, and classes.
- Writing small, single-purpose functions at the same level of abstraction.
- Adding guard clauses and error handling to make code logic cleaner.
- Configuring code through object properties rather than hardcoding values.
Groovy is a dynamic language for the Java Virtual Machine that aims to provide an alternative to Java for those seeking a more concise and expressive syntax. It is compatible with Java and allows Java code to be called from Groovy and vice versa. Groovy reduces boilerplate code through features like optional typing, closures/lambdas, operator overloading, and dynamic method dispatch. It also provides concise syntax for lists, maps, ranges, and other common data structures.
Value objects express “‘what’ something is rather than ‘who’ or ‘which’ it is.” In other words, values lack identity.
For example, the number 10 or the color red - all instances of 10 are conceptually equal to all other instances of 10, and likewise, red is always red. Two red bikes, however, have distinct identities.
We’ll explore how extracting value objects can simplify the challenge of bringing the real-world to bear as software. Then, we’ll touch on some strategies for integrating value objects with everyone’s favorite ORM, ActiveRecord.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
Anonymous classes in PHP 7 allow for the definition of classes without specifying a name. This document discusses what anonymous classes are, how to use them, and some limitations. Key points include: anonymous classes can implement interfaces and extend classes, inherit traits, and be used for test mocking and one-off objects due to their dynamic nature. However, they cannot be serialized, have limited scoping, and lack documentation.
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014hwilming
The slide to the Java User Group Talk Exploring Ceylon from Gavin King.
Abstrakt:
Ceylon is a new programming language designed for writing large programs in teams. The language emphasizes readability, modularity, typesafety, and tooling. Ceylon programs execute on Java and JavaScript virtual machines. In this session, Gavin King will talk about the ideas behind Ceylon and demonstrate the language, its type system, its module architecture, and its IDE.
Speaker:
Gavin King leads the Ceylon project at Red Hat. He is the creator of Hibernate, a popular object/relational persistence solution for Java, and the Seam Framework, an application framework for enterprise Java. He's contributed to the Java Community Process as JBoss and then Red Hat representative for the EJB and JPA specifications and as lead of the CDI specification.
Now he works full time on Ceylon, polishing the language specification, developing the compiler frontend, and thinking about the SDK and future of the platform. He's still a fan of Java, and of other languages, especially Smalltalk, Python, and ML.
This document provides an overview of object-oriented programming concepts in Python including objects, classes, inheritance, polymorphism, and encapsulation. It defines key terms like objects, classes, and methods. It explains how to create classes and objects in Python. It also discusses special methods, modules, and the __name__ variable.
Object Oriented Programming with PHP 5 - More OOPWildan Maulana
The document discusses object-oriented programming concepts in PHP 5 such as class information functions, checking if a class exists, finding loaded classes, checking for methods and properties, class types, and class names. It also covers exception handling, iterators, the ArrayObject class, serialization, cloning, autoloading classes, and method chaining in PHP 5 OOP.
Scala presentation by Aleksandar ProkopecLoïc Descotte
This document provides an introduction to the Scala programming language. It discusses how Scala runs on the Java Virtual Machine, supports both object-oriented and functional programming paradigms, and provides features like pattern matching, immutable data structures, lazy evaluation, and parallel collections. Scala aims to be concise, expressive, and extensible.
The Ring programming language version 1.5.2 book - Part 6 of 181Mahmoud Samir Fayed
The document provides an overview of the Ring programming language and highlights new features in version 1.5. Key points include:
- Ring is a dynamic and weakly typed scripting language that uses lexical scoping and allows dynamic typing.
- New applications like a video player, music player, and Windows startup manager were added.
- Libraries for graphics, web development, objects, and debugging were improved.
- The virtual machine was enhanced with function tracing and an interactive debugger.
- Syntax was made more flexible and a type hints library was added.
This document discusses Kotlin delegation and how it can be used to extend class behavior without subclassing. It provides examples of external and internal delegation in Kotlin. It also discusses how properties in Kotlin can be delegated to other objects by implementing interfaces like ReadOnlyProperty or using standard delegates from the Kotlin library. Real-world use cases demonstrated include binding views in Android, using dependency injection frameworks like Dagger, creating custom views, and binding shared preferences in a type-safe way. The document encourages exploring how to build type-safe APIs on top of other APIs like bundles and cursors using delegation.
The document is a slide presentation on Scala that provides an introduction to the language in 90 minutes or less. It covers Scala basics like being object oriented and functional, static typing, compilation to JVM bytecode, and interoperability with Java. It also discusses Scala tools, its use in open source projects and industry, recommended books, and jobs involving Scala. Code examples are provided to demonstrate Hello World programs, variables, methods, conditionals, sequences, and closures in Scala.
Lecture on Rubinius for Compiler Construction at University of TwenteDirkjan Bussink
This document summarizes Rubinius, an implementation of the Ruby programming language that includes a bytecode virtual machine written in C++ and Ruby. Some key points:
- Rubinius compiles Ruby code to bytecode that runs on its built-in virtual machine. This provides performance improvements over interpreting Ruby code.
- The virtual machine is implemented in both C++ and Ruby to provide flexibility. It can inline methods, perform just-in-time compilation, and garbage collect memory.
- Rubinius aims to be a complete Ruby implementation while also improving performance through techniques like inline caching, profiling, and garbage collection optimizations.
Creating Domain Specific Languages in PythonSiddhi
This document discusses domain specific languages (DSLs) and provides examples of creating DSLs in Python. It explains that DSLs allow users to work in specialized mini-languages tailored to specific problem domains. As examples, it discusses SQL as a DSL for databases and regular expressions as a DSL for patterns. It then demonstrates how to create an external DSL for defining forms using PyParsing and an internal DSL for the same using Python features like metaclasses. The document concludes that DSLs make code easier to read, write and maintain for non-programmers.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 1:
- Decorators
- Descriptors
- Metaclasses
- Multiple inheritance
Object Oriented Programming (OOP) allows developers to organize complex programs using classes and objects. OOP uses concepts like encapsulation, inheritance and polymorphism to keep data and functionality together in objects. The basic building blocks in OOP are classes, which define the properties and methods of an object, and objects, which are instances of classes. Classes can inherit properties and methods from parent classes, and objects can be identified and compared using operators like instanceof. Magic methods allow objects to override default behavior for operations like property access, method calling and object destruction.
Hammer of the Sysadmins based on puppet, git and redmine. Managing complex infrastructure producing 1/3 of slovak peering traffic in peaks. joj.sk, noviny.sk, huste.tv, tipsportextraliga.sk, prohokej.sk
The document discusses principles of writing clean code, including:
- Using consistent code style and formatting through style guides and linters.
- Avoiding duplicate code through principles like DRY.
- Using intention-revealing names for variables, functions, and classes.
- Writing small, single-purpose functions at the same level of abstraction.
- Adding guard clauses and error handling to make code logic cleaner.
- Configuring code through object properties rather than hardcoding values.
Groovy is a dynamic language for the Java Virtual Machine that aims to provide an alternative to Java for those seeking a more concise and expressive syntax. It is compatible with Java and allows Java code to be called from Groovy and vice versa. Groovy reduces boilerplate code through features like optional typing, closures/lambdas, operator overloading, and dynamic method dispatch. It also provides concise syntax for lists, maps, ranges, and other common data structures.
Value objects express “‘what’ something is rather than ‘who’ or ‘which’ it is.” In other words, values lack identity.
For example, the number 10 or the color red - all instances of 10 are conceptually equal to all other instances of 10, and likewise, red is always red. Two red bikes, however, have distinct identities.
We’ll explore how extracting value objects can simplify the challenge of bringing the real-world to bear as software. Then, we’ll touch on some strategies for integrating value objects with everyone’s favorite ORM, ActiveRecord.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
Anonymous classes in PHP 7 allow for the definition of classes without specifying a name. This document discusses what anonymous classes are, how to use them, and some limitations. Key points include: anonymous classes can implement interfaces and extend classes, inherit traits, and be used for test mocking and one-off objects due to their dynamic nature. However, they cannot be serialized, have limited scoping, and lack documentation.
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014hwilming
The slide to the Java User Group Talk Exploring Ceylon from Gavin King.
Abstrakt:
Ceylon is a new programming language designed for writing large programs in teams. The language emphasizes readability, modularity, typesafety, and tooling. Ceylon programs execute on Java and JavaScript virtual machines. In this session, Gavin King will talk about the ideas behind Ceylon and demonstrate the language, its type system, its module architecture, and its IDE.
Speaker:
Gavin King leads the Ceylon project at Red Hat. He is the creator of Hibernate, a popular object/relational persistence solution for Java, and the Seam Framework, an application framework for enterprise Java. He's contributed to the Java Community Process as JBoss and then Red Hat representative for the EJB and JPA specifications and as lead of the CDI specification.
Now he works full time on Ceylon, polishing the language specification, developing the compiler frontend, and thinking about the SDK and future of the platform. He's still a fan of Java, and of other languages, especially Smalltalk, Python, and ML.
This document provides an overview of object-oriented programming concepts in Python including objects, classes, inheritance, polymorphism, and encapsulation. It defines key terms like objects, classes, and methods. It explains how to create classes and objects in Python. It also discusses special methods, modules, and the __name__ variable.
Object Oriented Programming with PHP 5 - More OOPWildan Maulana
The document discusses object-oriented programming concepts in PHP 5 such as class information functions, checking if a class exists, finding loaded classes, checking for methods and properties, class types, and class names. It also covers exception handling, iterators, the ArrayObject class, serialization, cloning, autoloading classes, and method chaining in PHP 5 OOP.
Scala presentation by Aleksandar ProkopecLoïc Descotte
This document provides an introduction to the Scala programming language. It discusses how Scala runs on the Java Virtual Machine, supports both object-oriented and functional programming paradigms, and provides features like pattern matching, immutable data structures, lazy evaluation, and parallel collections. Scala aims to be concise, expressive, and extensible.
The Ring programming language version 1.5.2 book - Part 6 of 181Mahmoud Samir Fayed
The document provides an overview of the Ring programming language and highlights new features in version 1.5. Key points include:
- Ring is a dynamic and weakly typed scripting language that uses lexical scoping and allows dynamic typing.
- New applications like a video player, music player, and Windows startup manager were added.
- Libraries for graphics, web development, objects, and debugging were improved.
- The virtual machine was enhanced with function tracing and an interactive debugger.
- Syntax was made more flexible and a type hints library was added.
This document discusses Kotlin delegation and how it can be used to extend class behavior without subclassing. It provides examples of external and internal delegation in Kotlin. It also discusses how properties in Kotlin can be delegated to other objects by implementing interfaces like ReadOnlyProperty or using standard delegates from the Kotlin library. Real-world use cases demonstrated include binding views in Android, using dependency injection frameworks like Dagger, creating custom views, and binding shared preferences in a type-safe way. The document encourages exploring how to build type-safe APIs on top of other APIs like bundles and cursors using delegation.
The document is a slide presentation on Scala that provides an introduction to the language in 90 minutes or less. It covers Scala basics like being object oriented and functional, static typing, compilation to JVM bytecode, and interoperability with Java. It also discusses Scala tools, its use in open source projects and industry, recommended books, and jobs involving Scala. Code examples are provided to demonstrate Hello World programs, variables, methods, conditionals, sequences, and closures in Scala.
Lecture on Rubinius for Compiler Construction at University of TwenteDirkjan Bussink
This document summarizes Rubinius, an implementation of the Ruby programming language that includes a bytecode virtual machine written in C++ and Ruby. Some key points:
- Rubinius compiles Ruby code to bytecode that runs on its built-in virtual machine. This provides performance improvements over interpreting Ruby code.
- The virtual machine is implemented in both C++ and Ruby to provide flexibility. It can inline methods, perform just-in-time compilation, and garbage collect memory.
- Rubinius aims to be a complete Ruby implementation while also improving performance through techniques like inline caching, profiling, and garbage collection optimizations.
Creating Domain Specific Languages in PythonSiddhi
This document discusses domain specific languages (DSLs) and provides examples of creating DSLs in Python. It explains that DSLs allow users to work in specialized mini-languages tailored to specific problem domains. As examples, it discusses SQL as a DSL for databases and regular expressions as a DSL for patterns. It then demonstrates how to create an external DSL for defining forms using PyParsing and an internal DSL for the same using Python features like metaclasses. The document concludes that DSLs make code easier to read, write and maintain for non-programmers.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 1:
- Decorators
- Descriptors
- Metaclasses
- Multiple inheritance
Object Oriented Programming (OOP) allows developers to organize complex programs using classes and objects. OOP uses concepts like encapsulation, inheritance and polymorphism to keep data and functionality together in objects. The basic building blocks in OOP are classes, which define the properties and methods of an object, and objects, which are instances of classes. Classes can inherit properties and methods from parent classes, and objects can be identified and compared using operators like instanceof. Magic methods allow objects to override default behavior for operations like property access, method calling and object destruction.
Hammer of the Sysadmins based on puppet, git and redmine. Managing complex infrastructure producing 1/3 of slovak peering traffic in peaks. joj.sk, noviny.sk, huste.tv, tipsportextraliga.sk, prohokej.sk
Tomáš Čorej: Configuration management & CFEngine3Jano Suchal
CFEngine is the oldest tool for configuration management that inspired Puppet & Chef. Features like model-based monitoring, promise theory and knowledge management support makes it an reasonable alternative for IT system automatization.
The document discusses the key concepts of metaprogramming in Ruby including dynamic method lookup, open classes, modules, callbacks, and dynamic method definition. Some examples provided include defining accessor methods using modules, extending classes with module methods, defining instance and class methods dynamically, and hooking into callbacks to add functionality. Metaprogramming allows code to generate and modify code at runtime enabling powerful abstractions.
This document provides an overview and walkthrough for mastering puppet configuration management. It introduces puppet and compares it to other solutions like Chef and CFEngine. It outlines puppet's client/server model and covers setting up the master directory structure and configuring agents. The document explains puppet's resource types and manifest syntax. It also provides instructions for setting up an environment and implementing a sample configuration for packages, services, and files.
Desarrollando aplicaciones web en minutosEdgar Suarez
This document provides an overview of the Ruby programming language, including:
- Its creation by Yukihiro Matsumoto in 1993 and key influences like Perl, Smalltalk, and Lisp.
- Its main features like dynamic typing, duck typing, readable syntax, metaprogramming capabilities, blocks, exceptions, and object orientation.
- How Ruby on Rails was created by David Heinemeier Hansson in 2004 to build web applications using Ruby.
- Common tasks when using Ruby like installing Ruby and Rails, generating models and migrations, associations, validations, and using the MVC framework.
Ruby is an object-oriented scripting language that is dynamically typed and supports duck typing. It was created in the 1990s by Yukihiro "Matz" Matsumoto and has gained popularity through its use in web frameworks like Ruby on Rails. This document provides an overview of the Ruby language, including its history, basic syntax like strings and methods, core data types, control structures, classes and inheritance. It also discusses tools used by Ruby developers like RubyGems, interactive Ruby shells, and practical applications of Ruby for web development, testing, and automation through scripting. Finally, it mentions the international Ruby community and local user groups.
Discussing language constructs with fellow developers in the context of solving a particular problem is something we do routinely. While most such conversations are productive and useful, a fair portion degenerate into angry brawls. A pattern we've observed in the latter situation is that a surprising number of times the argument is that "Why shouldn't I use language feature X to achieve objective Y- after all, the language supports X."
In this talk Aakash and Niranjan walk through a few features of the Ruby language which when used wisely allows programmers to solve problems elegantly but if they are used without caution can lead to bad code.
The document discusses Ruby and Ruby on Rails. It notes that Ruby is an object-oriented programming language created by Yukihiro Matsumoto in 1995. Ruby on Rails is a web application framework built on Ruby that was created by David Heinemeier Hansson in 2004. It follows the model-view-controller architectural pattern, separating applications into models, views, and controllers.
This document discusses metaprogramming in Ruby, including object models, method dispatching, evaluation using class_eval, instance_eval, and eval, hooks for intercepting events, and building domain-specific languages. It provides examples of extending classes and objects at runtime through techniques like singleton classes, evaluation contexts, and method missing to add new behaviors dynamically. It also covers fluent interfaces and chaining methods to build internal domain-specific languages.
Attributes Unwrapped: Lessons under the surface of active record.toster
Ведущий разработчик Ruby on Rails (Rails Core member) Джон Лейтон не так давно работал над совершенствованием реализации работы с атрибутами в Active Record. Он расскажет о своем опыте работы над важной для производительности областью Rails, даст советы и расскажет о техниках, которые могут быть применены к собственным приложениям слушателей.
Говоря о будущем, Джон также расскажет о своих идеях по изменению API работы с атрибутами в лучшую сторону; эти изменения могут появиться в Rails 4.0.
This document provides an overview of the Ruby programming language, including its history, philosophy, characteristics, applications, culture, syntax, built-in types, classes and methods, accessors, control flow, including code, modules, metaprogramming, web frameworks, web servers, shell scripting, testing, JRuby, and calling between Java and Ruby.
The document provides an overview of Ruby on Rails and its key components. It discusses how Rails is made up of several gems including Rails, ActiveSupport, ActionPack, ActiveRecord, ActiveResource and ActionMailer. It summarizes the purpose and functionality of each gem. For example, it states that ActiveRecord connects classes to database tables for persistence, while ActionPack handles routing, controllers and views.
The document provides techniques for designing beautiful Ruby APIs. It discusses 10 techniques: 1) argument processing, 2) code blocks, 3) module, 4) method_missing, 5) const_missing, 6) method chaining, 7) core extension, 8) class macro, 9) instance_eval, and 10) Class.new. For each technique, it provides examples of how it can be implemented and used to create clean, readable APIs in Ruby. It also includes a sub-talk on Ruby's object model and how metaprogramming works.
This document provides an overview of the Ruby programming language. It discusses Ruby's history, design, syntax features like classes, modules, blocks, and metaprogramming. It also covers Ruby implementations like MRI, JRuby, REE, and others. In 3 sentences:
Ruby is a dynamic, reflective, object-oriented scripting language created in the mid-1990s by Yukihiro Matsumoto. It supports features like classes, modules, blocks and closures, duck typing, and metaprogramming. Popular Ruby implementations include MRI, JRuby, REE, and others that provide the Ruby language on different platforms and virtual machines.
Ruby is a dynamic, open source object-oriented scripting language that is interpreted, not compiled. It supports features like garbage collection, exception handling, operator overloading, and just-in-time compilation. Ruby can be used for web development, system scripting, database programming, and GUI development. It uses classes and modules to support object-oriented programming concepts like inheritance, polymorphism, and mixins.
This document contains notes from a series of tips and quirks related to Ruby programming. It covers topics like local variables in different Ruby versions, differences between strings and symbols, using modules and classes, responding to super, object counting, finalizers, and calling procs. The document provides code examples to demonstrate various Ruby language features and behaviors.
This document provides an overview of the Ruby programming language. It discusses Ruby's clean and meaningful syntax, everything being an object, dynamic typing and duck typing, open classes, blocks, mixins, testing, standard library, and gems. Ruby aims to be productive and fun to use.
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesTchelinux
Sobre o palestrante: Formado na UFPel no início do ano corrente, trabalhou com desenvolvimento de hardware para TV digital durante a graduação. Entretanto, sempre foi apaixonado por belas linguagens de programação, e destas, Ruby é a que mais se destaca. Atualmente aguarda o mês de junho, quando começa a trabalhar na ThoughtWorks, em Porto Alegre.
- Ruby is an interactive, object-oriented programming language created by Yukihiro Matsumoto in 1995.
- Ruby on Rails is a web application framework built on Ruby that emphasizes convention over configuration and is optimized for programmer happiness.
- The document discusses Ruby and Ruby on Rails, providing an overview of their history, key principles like MVC, REST, and conventions used in Rails. It also provides examples of modeling data with classes and ActiveRecord in Rails.
The document discusses various Ruby concepts including object-oriented programming (OOP), metaprogramming, blocks, iterators, mixins, duck typing, classes, modules, inheritance, include/extend, yield, enumerable, comparable, symbol to proc, transactions, and file handling. It provides code examples to illustrate these concepts.
This document provides an overview of mocks and stubs in testing, using Ruby and RSpec examples. It establishes common terminology around mock objects, shows appropriate uses of mocks such as defining interfaces and simulating situations, and demonstrates abuses such as modifying the subject under test and creating "mock trainwrecks" that tie specs too tightly to implementation details. The goal is to understand best practices for using mocks to write clear, maintainable tests.
Rapid Development with Ruby/JRuby and Railselliando dias
This document discusses Ruby and Rails development. It provides an overview of Ruby as a scripting language created by Yukihiro Matsumoto in 1993 with a focus on readability. Key aspects of Ruby covered include conventions, classes, symbols, closures, duck typing, and metaprogramming. The document also discusses how JRuby allows Java developers to use Ruby on the JVM and benefit from Ruby tools like Rails.
This document provides an introduction to jRuby, which allows Ruby code to be run on the Java Virtual Machine. It discusses the history and creator of Ruby, Yukihiro "Matz" Matsumoto, and his goals for the language. It then provides a primer on Ruby syntax including booleans, strings, numbers, arrays, hashes, symbols, and classes. It demonstrates how Ruby code can interact with Java code when using jRuby, such as calling Java classes and methods from Ruby. It also discusses metaprogramming in Ruby and how jRuby enables cross-platform GUI development using Java libraries.
Similar to Postobjektové programovanie v Ruby (20)
The document discusses tips and tricks for improving code quality, including issues to avoid like mutable state and premature abstraction. It recommends outside-in development, starting with acceptance tests and unit testing using test-driven development. The use of immutable objects is emphasized to avoid temporal coupling and make code more maintainable. Additional techniques include smell-driven development to detect code smells and refactor as needed. Tools like rubocop, reek and mutant are also mentioned.
This document discusses search quality and optimization. It covers various metrics used to measure search quality like mean average precision and expected reciprocal rank. It also discusses using clickthrough data and implicit feedback to optimize search engines by analyzing query chains, repeated results, and A/B testing with interleaving. The document promotes a service called searchd.co that provides search analytics to help identify problems, test changes safely, and improve the search experience.
This document discusses various topics related to machine learning including recommender systems, search engines, academic papers, and challenges. It also provides biographical information about the author, their work experience including with recommender engines and news recommendations, and their invitation for others to contact them to discuss serious recommenders and search.
This document discusses machine learning techniques for ranking and recommending information. It covers several academic papers on learning to rank, optimizing search engines using click data, and challenges in diversification, group recommendations, and context-aware recommendations. Examples of context include time of day, device, mood, season, and location. The document encourages getting in touch to discuss serious recommenders and search.
How the query planner in PostgreSQL works? Index access methods, join execution types, aggregation & pipelining. Optimizing queries with WHERE conditions, ORDER BY and GROUP BY. Composite indexes, partial and expression indexes. Exploiting assumptions about data and denormalization.
Garelic: Google Analytics as App Performance monitoringJano Suchal
This document describes Garelic, an open source tool that allows using Google Analytics for app performance monitoring. It explains how Garelic uses Google Analytics features like User Timing and Custom Variables to track metrics like controller and ActiveRecord response times. Garelic implements this by monkey patching Rails and subscribing to ActiveSupport notifications to capture timing data and report it to Google Analytics. Some limitations are that it can't track redirects, AJAX, or jobs, and page caching breaks reports. Ideas for future work include error tracking and thresholding for slow responses only.
Temporálne databázy umožňujú zachytávať históriu biznisových a systémových zmien dát a poskytujú prostriedky na pohodlnú prácu s historickými dátami. Majú široké uplatnenie v rôznych sektoroch ako napríklad poisťovníctvo, bankovníctvo či rezervačné systémy. Umožňujú jednoduché kontrolovanie vykonaných zmien, návrat k predchádzajúcim stavom dát a rôzne analytické dotazy nad históriou. V rámci prezentácie sa budem venovať všeobecnému prehľadu oblasti, existujúcim štandardom (napr. SQL:2011) a riešeniam a na jednoduchých príkladoch predvediem hlavnú funkcionalitu temporálnych databáz. Nakoniec ešte načrtnem možnosti pridania temporálnej podpory do Postgresql a porozprávam aj o tom, ako sa snažím temporálnu podporu dostať do oficiálneho release a čo všetko také niečo obnáša.
Profiling and monitoring ruby & rails applicationsJano Suchal
The document discusses profiling and monitoring Ruby on Rails applications. It provides examples of using the ruby-prof gem to profile a Ruby script and identify bottlenecks. It also discusses using NewRelic to monitor production applications and track metrics like web transactions, SQL queries, background jobs, and errors. Common performance issues mentioned include the N+1 query problem, lack of indexing, unnecessary ActiveRecord loading, default GC parameters, and unknown abstraction internals.
PostgreSQL: Advanced features in practiceJano Suchal
The document discusses several advanced features of PostgreSQL including:
1) Transactional DDL which allows DDL statements to be executed transactionally.
2) Cost-based query optimization and graphical EXPLAIN plans which help choose the most efficient query plan.
3) Features like partial indexes, function indexes, k-nearest search, views, and window functions which provide powerful ways to query and analyze data.
14. Dedenie
class Instrument
def tune
...
end
end
class Violin < Instrument
def play
tune
"Taa daa"
end
end
15. Overloading v ruby nefunguje
class Instrument
def play
"Ta da"
end
def play(octave)
"Ta da #{octave}"
end
end
i = Instrument.new
i.play #=> ArgumentError: wrong number of arguments (0 for 1)
i.play('c dur') #=> "Ta da c dur"
16. Overriding
class Instrument
def play
"Ta da"
end
end
class Violin < Instrument
def play
"Tiii diii tiii"
end
end
v = Violin.new
v.play #=> "Tiii diii tiii"
17. Polymorfia
class Instrument
def play
end
end
class Violin < Instrument
def play
"Taa daa"
end
end
class Drum < Instrument
def play
"Dum dum"
end
end
orchestra = [Violin.new, Violin.new, Drum.new]
orchestra.each { |i| i.play }
#=> "Taa daa", "Taa daa", "Dum dum"
20. ActiveSupport try
p = Person.find(params[:id])
p.address.downcase
#=> NoMethodError: undefined method `downcase'
# for nil:NilClass
p.address.try :downcase #=> nil
21. Aj metóda
class Person
def greet(other_person)
"Ahoj #{other_person}"
end
end
m = Person.instance_method(:greet)
m.class #=> UnboundMethod
m.arity #=> 1
m.name #=> :greet
m.parameters #=> [[:req, :other_person]]
24. Modul ako namespace
module Rubyslava
class OOP
end
end
module Pyvo
class OOP
end
end
Rubyslava::OOP == Pyvo::OOP #=> false
25. Modul ako nositeľ kódu
module Rubyslava
def hello
"Rubyslava"
end
end
26. Mixiny
class RubyslavaAPyvo
include Rubyslava
end
rp = RubyslavaAPyvo.new
rp.hello #=> "Rubyslava"
class RubyslavaAPyvo
extend Rubyslava
end
RubyslavaAPyvo.hello #=> "Rubyslava"
27. Viacnásobné dedenie
class RubyslavaAPyvo < Array
include Rubyslava, Pyvo
end
RubyslavaAPyvo.ancestors
#=> [RubyslavaAPyvo, Rubyslava, Pyvo
# Array, Object, Kernel, BasicObject]
29. module AdditionalBehaviour
def show
greet
end
end
class Test
include AdditionalBehaviour
def greet
"hello"
end
end
Test.new.show #=> "hello"
30. module GreetingBehavior
def greet
"hello"
end
end
module RelyOnGreetingBehavior
def show
greet
end
end
class Test
include GreetingBehavior, RelyOnGreetingBehavior
end
Test.new.show #=> "hello"
31. Zo života
Enumerable
acts_as_..
ActiveSupport::Concern
32. class Tree
include Enumerable
def each(&block)
leafs.each do { |n| yield n }
end
end
t = Tree.new
t.map
t.inject
t.sum
...
33. class Post
acts_as_taggable
end
p = Post.find(1)
p.tag_list #=> ["Ruby", "OOP"]
34. ActiveSupport::Concern
module Annotatable
extend ActiveSupport::Concern
included do
has_many :notes, :as => :annotatable,
:order => "created_at DESC"
end
def most_annotated
joins(:notes).group(:id).order("COUNT(*) DESC").first
end
end
class Project < ActiveRecord::Base
include Annotatable, Importable, Versionable
end
42. Singleton
class Logger
def initialize
@log = File.open("log.txt", "a")
end
@@instance = Logger.new
def self.instance
@@instance
end
def log(msg)
@log.puts(msg)
end
private_class_method :new
end
Logger.instance.log('message 1')
43. Singleton (lepšie)
require 'singleton'
class Logger
include Singleton
def initialize
@log = File.open("log.txt", "a")
end
def log(msg)
@log.puts(msg)
end
end
Logger.instance.log('message 2')
50. Delegator
include 'forwardable'
class Car
extend Forwardable
def_delegators :@car_computer, :velocity,
:distance
def initialize
@car_computer = CarComputer.new
end
end
c = Car.new
c.velocity
c.distance
52. Proxy
require 'delegate'
class Future < SimpleDelegator
def initialize(&block)
@_thread = Thread.start(&block)
end
def __getobj__
__setobj__(@_thread.value) if @_thread.alive?
super
end
end
google = Future.new do
Net::HTTP.get_response(URI('http://www.google.com')).body
end
yahoo = Future.new do
Net::HTTP.get_response(URI('http://www.yahoo.com')).body
end
puts google
puts yahoo
55. class Game
def play
prepare_board
initialize_score
while not end_of_game?
make_move
end
end
end
class Carcassonne < Game
def make_move
tile = tiles.pick_random
...
end
end
class Agricola < Game
def make_move
peasant = select_peasant
...
end
end
57. class Person
def say
"#{@name}"
end
end
class Family
attr_accessor :members
def initialize(members)
@members = members
end
def say
@members.each { |m| m.say }
end
end
f = Family.new(Person.new('Janko'), Person.new('Tomas'))
t = Family.new(Person.new('Ferko'), f)
t.say #=> "Ferko", "Janko", "Tomas"
59. class FileLogger < Logger
def log(message)
File.open('a') { |f| f << message }
end
end
class DatabaseLogger < Logger
def log(message)
Log.create(:message => message)
end
end
61. class TrafficLight
include AlterEgo
state :proceed, :default => true do
handle :color do
"green"
end
transition :to => :caution, :on => :cycle!
end
state :caution do
handle :color do
"yellow"
end
transition :to => :stop, :on => :cycle!
end
state :stop do
handle :color do
"red"
end
transition :to => :proceed, :on => :cycle!
end
end
64. class Comment < ActiveRecord::Base
end
class CommentObserver < ActiveRecord::Observer
def after_save(comment)
Notifications.deliver_comment("admin@do.com",
"New comment was posted", comment)
end
end
67. class Container
def add(node)
if node.kind_of? Array
node.each { |n| @nodes << n }
else
@nodes << node
end
end
end
container.add(Tree.new('a', 'b')) #=> ???
68. class Container
def add(node)
unless node.respond_to? :each
node = [node]
end
node.each { |n| @nodes << n }
end
end
container.add(Tree.new('a', 'b')) #=> ['a', 'b']
69. Protipríklad
ActiveRecord::sanitize_sql_for_assignment
def sanitize_sql_for_assignment(assignments)
case assignments
when Array
sanitize_sql_array(assignments)
when Hash
sanitize_sql_hash_for_assignment(assignments)
else assignments
end
end
70. Visitor + typy
def visit object
method = "visit_#{object.class.name}"
send method, object
end
module Arel
module Visitors
class WhereSql < Arel::Visitors::ToSql
def visit_Arel_Nodes_SelectCore o
"WHERE #{o.wheres.map { |x| visit x }.join ' AND ' }"
end
end
end
end
71. Shotgun surgery
ak niečo mením tak musím na viacerých
miestach
crosscutting concerns
AOP (AspectJ)
75. Autorizácia
class DocumentController < ApplicationController
before_filter :find_document
def show
# render @document
end
private
def find_document
@document = Document.find_by_id(params[:id])
end
end
76. class DocumentController < ApplicationController
before_filter :find_document
around_filer :authorize
def show
# render @document
end
private
def find_document
@document = Document.find_by_id(params[:id])
end
def authorize
if current_user.can_view?(@document)
yield
else
render :not_authorized
end
end
end
87. Dátová trieda
class SubjectController < ApplicationController
def show
if @subject.updated_at < Time.now - 2.weeks.ago
@subject.refresh
end
end
end
class Subject < ActiveRecord::Base
end
88. Dátová trieda 2
class SubjectController < ApplicationController
def show
@subject.update_if_stale
end
end
class Subject < ActiveRecord::Base
def update_if_stale
refresh if updated_at < Time.now - 2.weeks.ago
end
end
class Person < Subject
def update_if_stale
# update vsetky firmy kde je subjekt
end
end
89. Komentáre
# download new version of article
def perform(x)
# load article from the url 'x'
...
end
def download_article(url)
...
end