The document compares and contrasts Kibana and Grafana. It discusses that in Kibana, user privileges are based on base and feature privileges that determine read and write access. In Grafana, user permission is determined by their role, team access, and specific dashboard/folder permissions. Both tools allow for visualizing time-series data, but Kibana focuses on log analysis using Elasticsearch while Grafana supports multiple data sources and is designed more for metrics and monitoring. Key differences include Kibana being integrated with ELK while Grafana supports various plugins, and Grafana having built-in alerts while Kibana relies on plugins.
How you can contribute to Apache CassandraYuki Morishita
Yuki Morishita discusses how to contribute to the Apache Cassandra project, including submitting code patches as a programmer or contributing in other ways such as reporting bugs, testing patches, sharing use cases, and helping others on mailing lists and IRC channels. Programmers are instructed on tools, coding style, testing using ccm and cassandra-dtest, and submitting patches via JIRA. Non-programmers are encouraged to report bugs, test patches, blog/tweet experiences, and assist others on forums.
The document discusses various Flutter widgets including BottomNavigationBar, Row, Column, Stack, Expanded, and Padding. It explains how to use these widgets to layout apps and position elements. It also covers asynchronous programming concepts like async/await and Futures and how they are used to handle asynchronous code in Dart. Key topics are future chaining with then/catch, async functions, and awaiting Futures. The document ends with questions about Futures and print order.
React is a JavaScript framework used for building user interfaces. It uses components as the building blocks for user interfaces and embraces functional programming principles like immutable data and pure functions. The key aspects of React include JSX which allows writing HTML in JavaScript files, components which are functions that output HTML, and hooks which allow components to interact with state and lifecycle events.
C++/WinRT is designed to give C++ developers uncompromising performance as well as amazing productivity. Come and learn how to make effective use of C++ for the most demanding projects, whether it’s a system component, desktop or console app, or UWP app. In this session, we’ll also walk you through our early support for creating a XAML application in standard C++ and provide tips and guidance on how to move your C++/CX code to use standard C++ with C++/WinRT.
gRPC can help minimize the barrier of cross-system communication by providing language-agnostic API definitions, backward and forward compatible versioning with protocol buffers, and pluggable load balancing and tracing. You will see how to quickly get up and running with the gRPC framework using Node.js from creating a protocol definition, creating meaningful health checks, and securing the endpoint. Additionally, this session will go over best practices and how to take full advantage of what gRPC has to offer.
The document compares and contrasts Kibana and Grafana. It discusses that in Kibana, user privileges are based on base and feature privileges that determine read and write access. In Grafana, user permission is determined by their role, team access, and specific dashboard/folder permissions. Both tools allow for visualizing time-series data, but Kibana focuses on log analysis using Elasticsearch while Grafana supports multiple data sources and is designed more for metrics and monitoring. Key differences include Kibana being integrated with ELK while Grafana supports various plugins, and Grafana having built-in alerts while Kibana relies on plugins.
How you can contribute to Apache CassandraYuki Morishita
Yuki Morishita discusses how to contribute to the Apache Cassandra project, including submitting code patches as a programmer or contributing in other ways such as reporting bugs, testing patches, sharing use cases, and helping others on mailing lists and IRC channels. Programmers are instructed on tools, coding style, testing using ccm and cassandra-dtest, and submitting patches via JIRA. Non-programmers are encouraged to report bugs, test patches, blog/tweet experiences, and assist others on forums.
The document discusses various Flutter widgets including BottomNavigationBar, Row, Column, Stack, Expanded, and Padding. It explains how to use these widgets to layout apps and position elements. It also covers asynchronous programming concepts like async/await and Futures and how they are used to handle asynchronous code in Dart. Key topics are future chaining with then/catch, async functions, and awaiting Futures. The document ends with questions about Futures and print order.
React is a JavaScript framework used for building user interfaces. It uses components as the building blocks for user interfaces and embraces functional programming principles like immutable data and pure functions. The key aspects of React include JSX which allows writing HTML in JavaScript files, components which are functions that output HTML, and hooks which allow components to interact with state and lifecycle events.
C++/WinRT is designed to give C++ developers uncompromising performance as well as amazing productivity. Come and learn how to make effective use of C++ for the most demanding projects, whether it’s a system component, desktop or console app, or UWP app. In this session, we’ll also walk you through our early support for creating a XAML application in standard C++ and provide tips and guidance on how to move your C++/CX code to use standard C++ with C++/WinRT.
gRPC can help minimize the barrier of cross-system communication by providing language-agnostic API definitions, backward and forward compatible versioning with protocol buffers, and pluggable load balancing and tracing. You will see how to quickly get up and running with the gRPC framework using Node.js from creating a protocol definition, creating meaningful health checks, and securing the endpoint. Additionally, this session will go over best practices and how to take full advantage of what gRPC has to offer.
The document discusses Alfresco security best practices. It covers topics such as hardening the network and operating system, implementing firewall rules, assessing vulnerabilities, and compliance with standards. Best practices for the Alfresco implementation include staying current with patches, enforcing strong permissions, and deleting content when it is removed. The document provides an overview of security considerations for the Alfresco architecture, mobile access, and other deployment aspects.
https://youtu.be/_yLt_abcK2w
Angular is a TypeScript-based open-source front-end platform that makes it easy to build applications with in web/mobile/desktop. The major features of this framework such as declarative templates, dependency injection, end to end tooling, and many more other features are used to ease the development.
Angular 7 is a Javascript framework built around the concept of components, and more precisely, with the Web Components standard in mind. It was rewritten from scratch by the Angular team using Typescript (although we can use it with ES5, ES6, or Dart as well).
Angular 7 is a big change for us compared to 1.x. Because it is a completely different framework than 1.x, and is not backward-compatible. Angular 7 is written entirely in Typescript and meets the ECMAScript 6 specification
angular interview questions and answers, angular 7 interview questions and answers, angular interview question, angular interview questions and answers for experienced, angular 7 interview questions, angular 6 interview questions,
angular interview questions, angular 6 interview questions and answers, angular 2 interview questions, angular7, angular 5 interview questions, angular interview, angular 2 interview questions and answers, angular questions and answers
The Spring Framework is an open-source Java platform that provides comprehensive infrastructure support for developing robust Java applications easily and rapidly. It was initially created by Rod Johnson in 2002 and released under the Apache 2.0 license. Spring simplifies development through features like dependency injection and aspect-oriented programming. It includes modules for core functions, data access, web applications, and other services.
This document summarizes a keynote presentation about Angular 2.0.0. It discusses the growth of the Angular community from 1.5 million users in October 2015 to 1.2 million users in September 2016 for Angular 1 and 623k users for Angular 2 in September 2016. It also outlines Angular's major release cycle and provides an overview of the core features and extensions of the Angular framework.
1) Reactive programming is a new programming paradigm that is asynchronous and non-blocking, treating data flows as event-driven streams.
2) Traditional REST APIs are synchronous and blocking with limitations on concurrent users, while reactive programming supports asynchronous operations, uses fewer threads, and enables back pressure on data streams.
3) Key aspects of reactive programming include reactive streams specifications, publishers that represent data sources, subscribers, and asynchronous non-blocking libraries like RxJava and Project Reactor that implement the specifications.
This document discusses best practices for developing RESTful APIs. It begins by explaining that APIs should follow REST principles even if others are not, in order to be usable by others. It then shows an example of a non-RESTful API call. The document goes on to explain concepts like RESTful design, HTTP methods, resources, and HATEOAS. It provides examples of good and bad API patterns. It also introduces tools like appkr/fractal that can help build RESTful APIs in Laravel. Overall, the document provides guidance on how to properly structure APIs according to REST architectural principles.
What is React-Native?
Why React-Native?
How React-Native works in detail?
- Metro bundler
- Main Thread
- Shadow Thread
- Javascript Thread
Yoga Engine
Threads Communication in React-Native
Comparison with Flutter and Native
React-Native Components
Munander Maan presented an introduction to gRPC, a modern, fast and efficient open-source framework developed by Google. The presentation covered what gRPC is, how it works internally using Protocol Buffers, its advantages over REST APIs, how it achieves scalability, and different types of APIs that can be built with gRPC. The agenda included deep dives into gRPC internals, comparisons with REST, scalability, and API types.
What is a Angular Js ?
What is the main benefits of Angular Js ?
What is the difference between Angular js 1 and Angular js 2 ?
Structure of Angular Js ?
Choose of Language|Editor ?
Introduction of Components.
Template, Interpolation and Directives.
Data Binding and Pipes.
,Angular 2 is Javascript framework
Practical non blocking microservices in java 8Michal Balinski
How to write application in Java 8 that do not waste resources and which can maximize effective utilization of CPU/RAM. Comparison of blocking and non-blocking approach for I/O and application services. Based on microservices implementing simple business logic in security/cryptography/payments domain. Demonstration of following aspects:
* NIO at all edges of application
* popular libraries that support NIO
* single instance scalability
* performance metrics (incl. throughput and latency)
* resources utilization
* code readability with CompletableFuture
* application maintenance and debugging
All above based on our experiences gathered during development of software platforms at Oberthur Technologies R&D Poland.
(Jason Gustafson, Confluent) Kafka Summit SF 2018
Kafka has a well-designed replication protocol, but over the years, we have found some extremely subtle edge cases which can, in the worst case, lead to data loss. We fixed the cases we were aware of in version 0.11.0.0, but shortly after that, another edge case popped up and then another. Clearly we needed a better approach to verify the correctness of the protocol. What we found is Leslie Lamport’s specification language TLA+.
In this talk I will discuss how we have stepped up our testing methodology in Apache Kafka to include formal specification and model checking using TLA+. I will cover the following:
1. How Kafka replication works
2. What weaknesses we have found over the years
3. How these problems have been fixed
4. How we have used TLA+ to verify the fixed protocol.
This talk will give you a deeper understanding of Kafka replication internals and its semantics. The replication protocol is a great case study in the complex behavior of distributed systems. By studying the faults and how they were fixed, you will have more insight into the kinds of problems that may lurk in your own designs. You will also learn a little bit of TLA+ and how it can be used to verify distributed algorithms.
ASP.NET Web API is the de facto framework for building HTTP-based services in the .NET ecosystem. With its WCF and MVC lineage, Web API brings to the table better architecture, easier configuration, increased testability, and as always, it's customizable from top to bottom. But to properly use Web API it is not enough to get familiar with its architecture and API, you also need to really understand what HTTP is all about. HTTP is the most common application layer protocol in the world, and yet, not many web developers are familiar with HTTP concepts such as of chunking, caching, and persisted connections. In this full-day tutorial, we will focus on designing and implementing HTTP-based services with ASP.NET Web API, and you will learn how to better use it to implement the features provided by HTTP.
This is a talk on how you can monitor your microservices architecture using Prometheus and Grafana. This has easy to execute steps to get a local monitoring stack running on your local machine using docker.
Slides of the university I gave at Devoxx Belgium with Antonio Goncalves on CDI, Java EE and JBoss Forge.
Abstract:
-------
During this 3 hours university, you will learn some CDI basis, and will quickly dive into more advance CDI features (such as extension). Using JBoss Forge we will quickly generate a Java EE 7 web application, and then, following business requirements, we will add CDI functionalities.
This university talk will be a mixture of code and slides, focusing on CDI and Java EE 7.
--------
Video of the university is available on YouTube: http://youtu.be/LYKMaj4XKvg
Code and Slides on GitHub: https://github.com/antoinesd/cdi-forge-uni/tree/DevoxxBe2015
Flutter is an open-source mobile app SDK developed by Google that allows building high-performance apps for iOS and Android from a single codebase. It uses Dart as its programming language, has beautiful Material and Cupertino widgets, supports hot reload for fast development, and compiles to native ARM code for high performance across both platforms. Flutter apps are fully reactive and use widgets to define all visual elements, making for a simple and consistent development experience.
Prometheus is an open source monitoring tool that collects metrics from monitored applications and stores them for querying and alerting. Grafana is used to visualize the metrics collected by Prometheus through customizable dashboards. It connects Prometheus as a data source and fires queries to retrieve and display time-series data as graphs and visualizations. This allows monitoring of server status, resources, containers, probes, and other metrics to more easily track system performance and issues over time.
This document provides tips and techniques for researching users on GitHub and Stack Overflow to find their contact information. It outlines the types of information available on profiles, how to use Boolean search operators and tags, and tips for assessing a GitHub user profile in depth. Examples of specific searches are also included to find profiles by location, language used, resumes posted, and more. Other sites like Octohunt and internal search limitations are also briefly mentioned.
25 Real Life Tips In Ruby on Rails DevelopmentBelighted
This is a collection of small tips and tricks related to developing web applications using the Ruby on Rails framework.
These tips are gathered from my personal experience of 4 years working with the framework, including more than 2 years of professional work at Belighted.
The talk was given in the Ruby on Rails Developer Room at Fosdem 2010 (www.fosdem.org).
This document outlines an agenda for a talk on practical Rails development. The agenda will focus on RESTful Rails and additional bonuses, and will not cover testing, databases, security, caching and scaling, or internationalization. It provides an overview of Rails, describing it as an open-source web framework using the Model-View-Controller pattern to develop database-backed web applications in a pure-Ruby environment.
The document discusses Alfresco security best practices. It covers topics such as hardening the network and operating system, implementing firewall rules, assessing vulnerabilities, and compliance with standards. Best practices for the Alfresco implementation include staying current with patches, enforcing strong permissions, and deleting content when it is removed. The document provides an overview of security considerations for the Alfresco architecture, mobile access, and other deployment aspects.
https://youtu.be/_yLt_abcK2w
Angular is a TypeScript-based open-source front-end platform that makes it easy to build applications with in web/mobile/desktop. The major features of this framework such as declarative templates, dependency injection, end to end tooling, and many more other features are used to ease the development.
Angular 7 is a Javascript framework built around the concept of components, and more precisely, with the Web Components standard in mind. It was rewritten from scratch by the Angular team using Typescript (although we can use it with ES5, ES6, or Dart as well).
Angular 7 is a big change for us compared to 1.x. Because it is a completely different framework than 1.x, and is not backward-compatible. Angular 7 is written entirely in Typescript and meets the ECMAScript 6 specification
angular interview questions and answers, angular 7 interview questions and answers, angular interview question, angular interview questions and answers for experienced, angular 7 interview questions, angular 6 interview questions,
angular interview questions, angular 6 interview questions and answers, angular 2 interview questions, angular7, angular 5 interview questions, angular interview, angular 2 interview questions and answers, angular questions and answers
The Spring Framework is an open-source Java platform that provides comprehensive infrastructure support for developing robust Java applications easily and rapidly. It was initially created by Rod Johnson in 2002 and released under the Apache 2.0 license. Spring simplifies development through features like dependency injection and aspect-oriented programming. It includes modules for core functions, data access, web applications, and other services.
This document summarizes a keynote presentation about Angular 2.0.0. It discusses the growth of the Angular community from 1.5 million users in October 2015 to 1.2 million users in September 2016 for Angular 1 and 623k users for Angular 2 in September 2016. It also outlines Angular's major release cycle and provides an overview of the core features and extensions of the Angular framework.
1) Reactive programming is a new programming paradigm that is asynchronous and non-blocking, treating data flows as event-driven streams.
2) Traditional REST APIs are synchronous and blocking with limitations on concurrent users, while reactive programming supports asynchronous operations, uses fewer threads, and enables back pressure on data streams.
3) Key aspects of reactive programming include reactive streams specifications, publishers that represent data sources, subscribers, and asynchronous non-blocking libraries like RxJava and Project Reactor that implement the specifications.
This document discusses best practices for developing RESTful APIs. It begins by explaining that APIs should follow REST principles even if others are not, in order to be usable by others. It then shows an example of a non-RESTful API call. The document goes on to explain concepts like RESTful design, HTTP methods, resources, and HATEOAS. It provides examples of good and bad API patterns. It also introduces tools like appkr/fractal that can help build RESTful APIs in Laravel. Overall, the document provides guidance on how to properly structure APIs according to REST architectural principles.
What is React-Native?
Why React-Native?
How React-Native works in detail?
- Metro bundler
- Main Thread
- Shadow Thread
- Javascript Thread
Yoga Engine
Threads Communication in React-Native
Comparison with Flutter and Native
React-Native Components
Munander Maan presented an introduction to gRPC, a modern, fast and efficient open-source framework developed by Google. The presentation covered what gRPC is, how it works internally using Protocol Buffers, its advantages over REST APIs, how it achieves scalability, and different types of APIs that can be built with gRPC. The agenda included deep dives into gRPC internals, comparisons with REST, scalability, and API types.
What is a Angular Js ?
What is the main benefits of Angular Js ?
What is the difference between Angular js 1 and Angular js 2 ?
Structure of Angular Js ?
Choose of Language|Editor ?
Introduction of Components.
Template, Interpolation and Directives.
Data Binding and Pipes.
,Angular 2 is Javascript framework
Practical non blocking microservices in java 8Michal Balinski
How to write application in Java 8 that do not waste resources and which can maximize effective utilization of CPU/RAM. Comparison of blocking and non-blocking approach for I/O and application services. Based on microservices implementing simple business logic in security/cryptography/payments domain. Demonstration of following aspects:
* NIO at all edges of application
* popular libraries that support NIO
* single instance scalability
* performance metrics (incl. throughput and latency)
* resources utilization
* code readability with CompletableFuture
* application maintenance and debugging
All above based on our experiences gathered during development of software platforms at Oberthur Technologies R&D Poland.
(Jason Gustafson, Confluent) Kafka Summit SF 2018
Kafka has a well-designed replication protocol, but over the years, we have found some extremely subtle edge cases which can, in the worst case, lead to data loss. We fixed the cases we were aware of in version 0.11.0.0, but shortly after that, another edge case popped up and then another. Clearly we needed a better approach to verify the correctness of the protocol. What we found is Leslie Lamport’s specification language TLA+.
In this talk I will discuss how we have stepped up our testing methodology in Apache Kafka to include formal specification and model checking using TLA+. I will cover the following:
1. How Kafka replication works
2. What weaknesses we have found over the years
3. How these problems have been fixed
4. How we have used TLA+ to verify the fixed protocol.
This talk will give you a deeper understanding of Kafka replication internals and its semantics. The replication protocol is a great case study in the complex behavior of distributed systems. By studying the faults and how they were fixed, you will have more insight into the kinds of problems that may lurk in your own designs. You will also learn a little bit of TLA+ and how it can be used to verify distributed algorithms.
ASP.NET Web API is the de facto framework for building HTTP-based services in the .NET ecosystem. With its WCF and MVC lineage, Web API brings to the table better architecture, easier configuration, increased testability, and as always, it's customizable from top to bottom. But to properly use Web API it is not enough to get familiar with its architecture and API, you also need to really understand what HTTP is all about. HTTP is the most common application layer protocol in the world, and yet, not many web developers are familiar with HTTP concepts such as of chunking, caching, and persisted connections. In this full-day tutorial, we will focus on designing and implementing HTTP-based services with ASP.NET Web API, and you will learn how to better use it to implement the features provided by HTTP.
This is a talk on how you can monitor your microservices architecture using Prometheus and Grafana. This has easy to execute steps to get a local monitoring stack running on your local machine using docker.
Slides of the university I gave at Devoxx Belgium with Antonio Goncalves on CDI, Java EE and JBoss Forge.
Abstract:
-------
During this 3 hours university, you will learn some CDI basis, and will quickly dive into more advance CDI features (such as extension). Using JBoss Forge we will quickly generate a Java EE 7 web application, and then, following business requirements, we will add CDI functionalities.
This university talk will be a mixture of code and slides, focusing on CDI and Java EE 7.
--------
Video of the university is available on YouTube: http://youtu.be/LYKMaj4XKvg
Code and Slides on GitHub: https://github.com/antoinesd/cdi-forge-uni/tree/DevoxxBe2015
Flutter is an open-source mobile app SDK developed by Google that allows building high-performance apps for iOS and Android from a single codebase. It uses Dart as its programming language, has beautiful Material and Cupertino widgets, supports hot reload for fast development, and compiles to native ARM code for high performance across both platforms. Flutter apps are fully reactive and use widgets to define all visual elements, making for a simple and consistent development experience.
Prometheus is an open source monitoring tool that collects metrics from monitored applications and stores them for querying and alerting. Grafana is used to visualize the metrics collected by Prometheus through customizable dashboards. It connects Prometheus as a data source and fires queries to retrieve and display time-series data as graphs and visualizations. This allows monitoring of server status, resources, containers, probes, and other metrics to more easily track system performance and issues over time.
This document provides tips and techniques for researching users on GitHub and Stack Overflow to find their contact information. It outlines the types of information available on profiles, how to use Boolean search operators and tags, and tips for assessing a GitHub user profile in depth. Examples of specific searches are also included to find profiles by location, language used, resumes posted, and more. Other sites like Octohunt and internal search limitations are also briefly mentioned.
25 Real Life Tips In Ruby on Rails DevelopmentBelighted
This is a collection of small tips and tricks related to developing web applications using the Ruby on Rails framework.
These tips are gathered from my personal experience of 4 years working with the framework, including more than 2 years of professional work at Belighted.
The talk was given in the Ruby on Rails Developer Room at Fosdem 2010 (www.fosdem.org).
This document outlines an agenda for a talk on practical Rails development. The agenda will focus on RESTful Rails and additional bonuses, and will not cover testing, databases, security, caching and scaling, or internationalization. It provides an overview of Rails, describing it as an open-source web framework using the Model-View-Controller pattern to develop database-backed web applications in a pure-Ruby environment.
1. The document discusses building web interfaces using Ruby on Rails. It covers useful Rails view helper techniques, plugins for adding helper and unobtrusive JavaScript functionality, and implementing common UI design patterns.
2. The handicraft_helper plugin allows building complex HTML structures more easily using a composite pattern. The handicraft_ujs plugin replaces Rails' default Ajax functionality with an unobtrusive JavaScript approach using jQuery.
3. The presentation demonstrates helper techniques, the two plugins, and implementing UI patterns like inline editing and sortable lists.
Ruby On Rails coding conventions, standards and best practicesDavid Paluy
This document discusses Ruby on Rails coding conventions and best practices. It covers philosophies like DRY (Don't Repeat Yourself) and convention over configuration. It also provides style guidelines for source code formatting, commenting practices, and naming conventions for classes, constants, and variables. Additional sections offer tips for formatting code readably and using Git commit messages effectively.
This document provides 10 tips for using Ruby on Rails more effectively:
1. Use the debugger tool to help troubleshoot applications.
2. Inline variable assignments can improve readability over multi-line conditional assignments.
3. Methods like Integer() and Float() raise exceptions on invalid input, and Hash#fetch avoids exceptions for missing keys.
4. Define constants for choices/options and use integers to reference them for improved performance and readability.
5. Be careful when using regular expressions with =~ as it returns an integer rather than true/false.
6. Eliminate redundant true/false checks in conditional logic like radio buttons.
7. The update_column
This document provides tips and best practices for creating effective presentations using visuals such as shapes, colors, images, and fonts. It recommends starting with a bold cover slide to grab attention, using visuals to highlight key points and sustain audience interest, and ending with a clear call to action. The overall message is that presentations should be visually appealing and easy to understand in order to effectively engage the audience.
This document discusses best practices for developing Ruby on Rails applications. It provides guidelines for structuring Rails code, including using model associations and callbacks, extracting logic into modules and composed classes, and leveraging patterns like observers to organize code. The document also recommends practices like keeping finders on their own models and using named scopes to improve code quality. It aims to help developers write clean, well-organized code that follows principles like DRY (Don't Repeat Yourself) and the Law of Demeter.
This document discusses several Ruby on Rails best practices including maintaining DRY code, using fat models and skinny controllers, avoiding N+1 queries, preventing SQL injection, using scopes to define common query patterns, and leveraging counter caches to improve performance. Key practices emphasized include organizing application logic in models, defining common queries with scopes, sanitizing user input to prevent SQL injection, preloading associated data to reduce the number of queries, and using counter caches to optimize counting related records.
MongoDB San Francisco 2013: Schema design presented by Jason Zucchetto, Consu...MongoDB
MongoDB’s basic unit of storage is a document. Documents can represent rich, schema-free data structures, meaning that we have several viable alternatives to the normalized, relational model. In this talk, we’ll discuss the tradeoff of various data modeling strategies in MongoDB using a library as a sample application. You will learn how to work with documents, evolve your schema, and common schema design patterns.
Boost your productivity!: Productivity tips for rails developers - Lightning ...Alberto Perdomo
This document provides 9 productivity tips for Rails developers:
1. Write custom Rails templates to speed up development
2. Tune your editor or IDE and use helpful bundles like Rails, Cucumber, and SASS
3. Store dotfiles in a repo and sync them using homesick to manage preferences
4. Use HIRB and WIRBLE to enhance the Rails console experience
5. Create Git and Rails aliases to speed up common commands like status, pull, push
6. Use Hermes to warn about assignments to protected attributes
7. Leverage Slowgrowl to find slow code paths
8. Create SSH aliases for easy deployment to staging and production servers
9
The document summarizes changes between Ruby 1.8 and Ruby 1.9. Key changes include ordered hashes, new hash syntax, external iterators using Enumerators, better encoding support through M17N, and changes to the threading model. The document provides an overview of Ruby 1.8 vs 1.9 and dives into specific changes like new syntax, library changes, and new features in Ruby 1.9 like external iterators and improved internationalization support.
This document discusses HTML5 and web application development. It begins with an overview of the anatomy of a web app, including setting up the server, using data services, and device detection. It then covers HTML5 features like new semantic tags, forms, multimedia capabilities using audio, video, and canvas. JavaScript APIs are discussed for geolocation, web storage, web SQL, and web workers. The document emphasizes that the mobile web is the most viable platform for cross-device applications.
Introduction to Active Record - Silicon Valley Ruby Conference 2007Rabble .
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.
Large data with Scikit-learn - Boston Data Mining Meetup - Alex PerrierAlexis Perrier
A presentation of adaptive classification and regression algorithms available in scikit-learn with a Focus on Stochastic Gradient Descent and KNN. Performance examples on 2 Large datasets are presented for SGD, Multinomial Naive Bayes, Perceptron and Passive Aggressive Algorithms.
Tips for creating a Self Organizing TeamsYves Hanoulle
The presentation was delivered in
Kjiv (AgileEE)
Geneve (AgileTourGeneve),
Agilis2009 (Iceland)
Scandinavian Developer Conference 2010
Agile Tour Bordeaux 2010
Modernizations prolong the economic service life of your overhead crane. They can provide a complete transformation of your existing crane as an alternative to replacing it and give you an opportunity to add current technologies.
The document outlines an agenda for learning how to build dashboards using the Dashing framework. The exercises include installing Dashing, adding and customizing widgets, updating widget data via REST API calls, and pulling data into widgets using jobs. Dashing allows creating customizable dashboards using premade or custom widgets that can be updated dynamically by connecting widget views to data through CoffeeScript.
Essa é uma apresentação que reúne algumas iniciativas e soluções que podem ser aplicadas no Governo Brasileiro e claro, serve para outros países também, pois a grande idéia é implementar alguns pontos do Governo Eletrônico, ou como prefiro chamar: Governo Aberto.
Adaptive pre-processing for streaming dataLARCA UPC
Many supervised learning approaches that adapt to changes in data distribution over time (e.g. concept drift) have been developed. The majority of them assume that data comes already pre-processed or that pre-processing is an integral part of a learning algorithm. In real application tasks data that comes from, e.g. sensor readings, is typically noisy, contains missing values, redundant features and a large part of model training needs to be devoted to data cleaning and pre-processing. As data is evolving over time, not only learning models, but also pre-processing mechanisms need to adapt. We will discuss under what circumstances it is beneficial to handle adaptivity of pre-processing and adaptivity of the learning model separately.
This document provides an overview of startup best practices including lean startup methodology, user stories, agile development practices, Git version control, metrics and analytics, and customer acquisition and retention strategies. It emphasizes frequent iteration and customer feedback to build the minimum viable product and validate business assumptions quickly.
This document provides an overview of RSpec testing for Rails applications. It discusses installing and generating RSpec files, different types of RSpec specs including model, controller, view, helper and routing specs. It covers spec syntax for expectations, matchers, factories and stubs. It also mentions features specs using Capybara, debugging techniques, JavaScript testing, and tools like DatabaseCleaner. The document is intended as a tutorial for setting up and writing different kinds of RSpec tests for a Rails application.
The document discusses exception handling in Ruby programming. It begins with an introduction to exception handling and why it is important. Then it covers the main concepts of exception handling in Ruby, including raise, rescue, ensure, retry and else. It also discusses some caveats and guidelines for exception handling, such as only using exceptions for truly unexpected situations and avoiding exception abuse.
Exception Handling: Designing Robust Software in RubyWen-Tien Chang
The document discusses exception handling in Ruby. It begins with explaining why exception handling is important for building robust software. It then covers various aspects of exception handling in Ruby including raising exceptions, rescuing exceptions, ensuring code is executed, retrying code, and using else blocks. It provides guidelines for proper exception handling practices such as only raising exceptions for unexpected situations. The document concludes by discussing different failure handling strategies like ensuring exception safety and categorizing operational errors versus programmer errors.
This document provides an overview introduction to the Ruby programming language. It discusses what Ruby is, basic syntax, key features like being dynamically typed and object-oriented, implementations, applications, and the ecosystem. It also covers topics like variables, data types, control flow, methods, classes, and encapsulation. Code examples are provided to demonstrate various language constructs.
The document summarizes RubyConf Taiwan 2012. Some key details include:
1) The conference had over 160 attendees including 35 speakers, with about 25 foreign attendees from countries like Japan.
2) Notable speakers included Yukihiro "Matz" Matsumoto, the creator of Ruby, and other Ruby Core Team members.
3) The two-day conference included 15 main talks and 23 lightning talks.
4) The organizers expressed thanks to the speakers, sponsors, and attendees for their participation in making the conference a success.
This document discusses the benefits of functional programming (FP) that the author learned. It begins by explaining how multithreading programs are difficult to write, test, and ensure thread safety due to mutable shared state. FP avoids these issues by not using mutable variables. The document then covers some key aspects of FP like recursion, higher-order functions, function composition, and immutable data structures. It provides examples in various languages to illustrate these concepts. The author argues that FP provides a good foundation for writing concurrent programs due to its avoidance of mutable state.
4. Agenda
• Concept: What’s good code?
• Move Code from Controller to Model
• RESTful best practices
• Model best practices
• Controller best practices
• View best practices
5. Warning! you should have testing before modify!
本次演講雖沒有提及測試,
但在修改重構程式前,
應有好的測試,
以確保程式於修改後執行無誤。
12. Best Practice Lesson 1:
Move code from Controller to
Model
action code 超過15行請注意
http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
13. 1.Move finder to named_scope
class PostsController < ApplicationController
def index
@public_posts = Post.find(:all, :conditions => { :state => 'public' },
:limit => 10,
:order => 'created_at desc')
@draft_posts = Post.find(:all, :conditions => { :state => 'draft' },
:limit => 10,
:order => 'created_at desc')
end
end
Before
14. class UsersController < ApplicationController
def index
@published_post = Post.published
@draft_post = Post.draft
end
end
class Post < ActiveRecord::Base
named_scope :published, :conditions => { :state => 'published' },
:limit => 10, :order => 'created_at desc')
named_scope :draft, :conditions => { :state => 'draft' },
:limit => 10, :order => 'created_at desc')
end
1.Move finder to named_scope
After
15. 2. Use model association
class PostsController < ApplicationController
def create
@post = Post.new(params[:post])
@post.user_id = current_user.id
@post.save
end
end
Before
16. class PostsController < ApplicationController
def create
@post = current_user.posts.build(params[:post])
@post.save
end
end
class User < ActiveRecord::Base
has_many :posts
end
2. Use model association
After
17. class PostsController < ApplicationController
def edit
@post = Post.find(params[:id)
if @post.current_user != current_user
flash[:warning] = 'Access denied'
redirect_to posts_url
end
end
end
3. Use scope access
不必要的權限檢查
Before
18. class PostsController < ApplicationController
def edit
# raise RecordNotFound exception (404 error) if not found
@post = current_user.posts.find(params[:id)
end
end
After
3. Use scope access
找不到自然會丟例外
19. 4.Add model virtual attribute
<% form_for @user do |f| %>
<%= text_filed_tag :full_name %>
<% end %>
class UsersController < ApplicationController
def create
@user = User.new(params[:user)
@user.first_name = params[:full_name].split(' ', 2).first
@user.last_name = params[:full_name].split(' ', 2).last
@user.save
end
end
Before
20. 4.Add model virtual attribute
class User < ActiveRecord::Base
def full_name
[first_name, last_name].join(' ')
end
def full_name=(name)
split = name.split(' ', 2)
self.first_name = split.first
self.last_name = split.last
end
end
example code from http://railscasts.com/episodes/16-virtual-attributes
After
21. <% form_for @user do |f| %>
<%= f.text_field :full_name %>
<% end %>
class UsersController < ApplicationController
def create
@user = User.create(params[:user)
end
end
example code from http://railscasts.com/episodes/16-virtual-attributes
After
22. 5. Use model callback
<% form_for @post do |f| %>
<%= f.text_field :content %>
<%= check_box_tag 'auto_tagging' %>
<% end %>
class PostController < ApplicationController
def create
@post = Post.new(params[:post])
if params[:auto_tagging] == '1'
@post.tags = AsiaSearch.generate_tags(@post.content)
else
@post.tags = ""
end
@post.save
end
end
Before
23. 5. Use model callback
class Post < ActiveRecord::Base
attr_accessor :auto_tagging
before_save :generate_taggings
private
def generate_taggings
return unless auto_tagging == '1'
self.tags = Asia.search(self.content)
end
end
After
24. <% form_for :note, ... do |f| %>
<%= f.text_field :content %>
<%= f.check_box :auto_tagging %>
<% end
class PostController < ApplicationController
def create
@post = Post.new(params[:post])
@post.save
end
end
After
25. 6. Replace Complex Creation
with Factory Method
class InvoiceController < ApplicationController
def create
@invoice = Invoice.new(params[:invoice])
@invoice.address = current_user.address
@invoice.phone = current_user.phone
@invoice.vip = ( @invoice.amount > 1000 )
if Time.now.day > 15
@invoice.delivery_time = Time.now + 2.month
else
@invoice.delivery_time = Time.now + 1.month
end
@invoice.save
end
end
Before
26. 6. Replace Complex Creation
with Factory Method
class Invoice < ActiveRecord::Base
def self.new_by_user(params, user)
invoice = self.new(params)
invoice.address = user.address
invoice.phone = user.phone
invoice.vip = ( invoice.amount > 1000 )
if Time.now.day > 15
invoice.delivery_time = Time.now + 2.month
else
invoice.delivery_time = Time.now + 1.month
end
end
end
After
27. class InvoiceController < ApplicationController
def create
@invoice = Invoice.new_by_user(params[:invoice], current_user)
@invoice.save
end
end
After
28. 7. Move Model Logic into the
Model
class PostController < ApplicationController
def publish
@post = Post.find(params[:id])
@post.update_attribute(:is_published, true)
@post.approved_by = current_user
if @post.create_at > Time.now - 7.days
@post.popular = 100
else
@post.popular = 0
end
redirect_to post_url(@post)
end
end
Before
29. 7. Move Model Logic into the
Model
class Post < ActiveRecord::Base
def publish
self.is_published = true
self.approved_by = current_user
if self.create_at > Time.now-7.days
self.popular = 100
else
self.popular = 0
end
end
end
After
30. class PostController < ApplicationController
def publish
@post = Post.find(params[:id])
@post.publish
redirect_to post_url(@post)
end
end
After
31. 8. model.collection_model_ids
(many-to-many)
class User < ActiveRecord::Base
has_many :user_role_relationship
has_many :roles, :through => :user_role_relationship
end
class UserRoleRelationship < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Role < ActiveRecord::Base
end
32. <% form_for @user do |f| %>
<%= f.text_field :email %>
<% for role in Role.all %>
<%= check_box_tag 'role_id[]', role.id, @user.roles.include?(role) %>
<%= role.name %>
<% end %>
<% end %>
class User < ApplicationController
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
@user.roles.delete_all
(params[:role_id] || []).each { |i| @user.roles << Role.find(i) }
end
end
end
Before
33. <% form_for @user do |f| %>
<% for role in Role.all %>
<%= check_box_tag 'user[role_ids][]', role.id, @user.roles.include?(role)
<%= role.name %>
<% end %>
<%= hidden_field_tag 'user[role_ids][]', '' %>
<% end %>
class User < ApplicationController
def update
@user = User.find(params[:id])
@user.update_attributes(params[:user])
# 相當於 @user.role_ids = params[:user][:role_ids]
end
end
After
34. Before
9. Nested Model Forms (one-to-one)
class Product < ActiveRecord::Base
has_one :detail
end
class Detail < ActiveRecord::Base
belongs_to :product
end
<% form_for :product do |f| %>
<%= f.text_field :title %>
<% fields_for :detail do |detail| %>
<%= detail.text_field :manufacturer %>
<% end %>
<% end %>
35. class Product < ApplicationController
def create
@product = Product.new(params[:product])
@details = Detail.new(params[:detail])
Product.transaction do
@product.save!
@details.product = @product
@details.save!
end
end
end
example code from Agile Web Development with Rails 3rd.
Before
36. After
9. Nested Model Forms (one-to-one)
Rails 2.3 new feature
class Product < ActiveRecord::Base
has_one :detail
accepts_nested_attributes_for :detail
end
<% form_for :product do |f| %>
<%= f.text_field :title %>
<% f.fields_for :detail do |detail| %>
<%= detail.text_field :manufacturer %>
<% end %>
<% end
37. After
class Product < ApplicationController
def create
@product = Product.new(params[:product])
@product.save
end
end
38. 10. Nested Model Forms (one-to-many)
class Project < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks
end
class Task < ActiveRecord::Base
belongs_to :project
end
<% form_for @project do |f| %>
<%= f.text_field :name %>
<% f.fields_for :tasks do |tasks_form| %>
<%= tasks_form.text_field :name %>
<% end %>
<% end %>
39. Nested Model Forms
before Rails 2.3 ?
• Ryan Bates’s series of railscasts on complex forms
• http://railscasts.com/episodes/75-complex-forms-part-3
• Recipe 13 in Advanced Rails Recipes book
41. Why RESTful?
RESTful help you to organize/name controllers, routes
and actions in standardization way
42. class EventsController < ApplicationController
def index
end
def show
end
def create
end
def update
end
def destroy
end
end
def watch_list
end
def add_favorite
end
def invite
end
def join
end
def leave
end
def feeds
end
def add_comment
end
def show_comment
end
def destroy_comment
end
def edit_comment
end
def approve_comment
end
def white_member_list
end
def black_member_list
end
def deny_user
end
def allow_user
end
def edit_managers
end
def set_user_as_manager
end
def set_user_as_member
end
Before
43. After
class EventsController < ApplicationController
def index; end
def show; end
end
class CommentsControlers < ApplicationController
def index; end
def create; end
def destroy; end
end
def FavoriteControllers < ApplicationController
def create; end
def destroy; end
end
class EventMembershipsControlers < ApplicationController
def create; end
def destroy; end
end
45. 1. Overuse route customizations
Find another resources
map.resources :posts do |post|
post.resources :comments
end
After
46. Suppose we has a event model...
class Event < ActiveRecord::Base
has_many :attendee
has_one :map
has_many :memberships
has_many :users, :through => :memberships
end
47. Can you answer how to design
your resources ?
• manage event attendees (one-to-many)
• manage event map (one-to-one)
• manage event memberships (many-to-many)
• operate event state: open or closed
• search events
• sorting events
• event admin interface
48. Learn RESTful design
my slide about restful:
http://www.slideshare.net/ihower/practical-rails2-350619
49. 2. Needless deep nesting
過度設計: Never more than one level
Before
map.resources :posts do |post|
post.resources :comments do |comment|
comment.resources :favorites
end
end
<%= link_to post_comment_favorite_path(@post, @comment, @favorite) %>
50. After
map.resources :posts do |post|
post.resources :comments
end
map.resources :comments do |comment|
comment.resources :favorites
end
<%= link_to comment_favorite_path(@comment, @favorite) %>
2. Needless deep nesting
過度設計: Never more than one level
51. 3. Not use default route
Before
map.resources :posts, :member => { :push => :post }
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
52. 3. Not use default route
After
map.resources :posts, :member => { :push => :post }
#map.connect ':controller/:action/:id'
#map.connect ':controller/:action/:id.:format'
map.connect 'special/:action/:id', :controller => 'special'
54. 1. Keep Finders on Their Own Model
class Post < ActiveRecord::Base
has_many :comments
def find_valid_comments
self.comment.find(:all, :conditions => { :is_spam => false },
:limit => 10)
end
end
class Comment < ActiveRecord::Base
belongs_to :post
end
class CommentsController < ApplicationController
def index
@comments = @post.find_valid_comments
end
end
Before
55. 1. Keep Finders on Their Own Model
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
named_scope :only_valid, :conditions => { :is_spam => false }
named_scope :limit, lambda { |size| { :limit => size } }
end
class CommentsController < ApplicationController
def index
@comments = @post.comments.only_valid.limit(10)
end
end
After
56. 2. Love named_scope
class PostController < ApplicationController
def search
conditions = { :title => "%#{params[:title]}%" } if params[:title]
conditions.merge!{ :content => "%#{params[:content]}%" } if params[:content]
case params[:order]
when "title" : order = "title desc"
when "created_at" : order = "created_at"
end
if params[:is_published]
conditions.merge!{ :is_published => true }
end
@posts = Post.find(:all, :conditions => conditions, :order => order,
:limit => params[:limit])
end
end
Before
example code from Rails Antipatterns book
57. 2. Love named_scope
After
class Post < ActiveRecord::Base
named_scope :matching, lambda { |column, value|
return {} if value.blank?
{ :conditions => ["#{column} like ?", "%#{value}%"] }
}
named_scope :order, lambda { |order|
{ :order => case order
when "title" : "title desc"
when "created_at" : "created_at"
end }
}
end
58. After
class PostController < ApplicationController
def search
@posts = Post.matching(:title, params[:title])
.matching(:content, params[:content])
.order(params[:order])
end
end
59. 3. the Law of Demeter
class Invoice < ActiveRecord::Base
belongs_to :user
end
<%= @invoice.user.name %>
<%= @invoice.user.address %>
<%= @invoice.user.cellphone %>
Before
60. 3. the Law of Demeter
class Invoice < ActiveRecord::Base
belongs_to :user
delegate :name, :address, :cellphone, :to => :user,
:prefix => true
end
<%= @invoice.user_name %>
<%= @invoice.user_address %>
<%= @invoice.user_cellphone %>
After
61. 4. DRY: Metaprogramming
class Post < ActiveRecord::Base
validate_inclusion_of :status, :in => ['draft', 'published', 'spam']
def self.all_draft
find(:all, :conditions => { :status => 'draft' }
end
def self.all_published
find(:all, :conditions => { :status => 'published' }
end
def self.all_spam
find(:all, :conditions => { :status => 'spam' }
end
def draft?
self.stats == 'draft'
end
def published?
self.stats == 'published'
end
def spam?
self.stats == 'spam'
end
end
Before
62. 4. DRY: Metaprogramming
class Post < ActiveRecord::Base
STATUSES = ['draft', 'published', 'spam']
validate_inclusion_of :status, :in => STATUSES
class << self
STATUSES.each do |status_name|
define_method "all_#{status}" do
find(:all, :conditions => { :status => status_name }
end
end
end
STATUSES.each do |status_name|
define_method "#{status_name}?" do
self.status == status_name
end
end
end
After
64. 5. Extract into Module
class User < ActiveRecord::Base
validates_presence_of :cellphone
before_save :parse_cellphone
def parse_cellphone
# do something
end
end
Before
65. # /lib/has_cellphone.rb
module HasCellphone
def self.included(base)
base.validates_presence_of :cellphone
base.before_save :parse_cellphone
base.send(:include,InstanceMethods)
base.send(:extend, ClassMethods)
end
module InstanceMethods
def parse_cellphone
# do something
end
end
module ClassMethods
end
end
After
66. class User < ActiveRecord::Base
include HasCellphone
end
After
67. 6. Extract to composed class
Before
# == Schema Information
# address_city :string(255)
# address_street :string(255)
class Customer < ActiveRecord::Base
def adddress_close_to?(other_customer)
address_city == other_customer.address_city
end
def address_equal(other_customer)
address_street == other_customer.address_street &&
address_city == other_customer.address_city
end
end
68. After
6. Extract to composed class
(value object)
class Customer < ActiveRecord::Base
composed_of :address, :mapping => [ %w(address_street street),
%w(address_city city) ]
end
class Address
attr_reader :street, :city
def initialize(street, city)
@street, @city = street, city
end
def close_to?(other_address)
city == other_address.city
end
def ==(other_address)
city == other_address.city && street == other_address.street
end
end
example code from Agile Web Development with Rails 3rd.
69. 7. Use Observer
class Project < ActiveRecord::Base
after_create :send_create_notifications
private
def send_create_notifications
self.members.each do |member|
ProjectNotifier.deliver_notification(self, member)
end
end
end
Before
70. class Project < ActiveRecord::Base
# nothing here
end
# app/observers/project_notification_observer.rb
class ProjectNotificationObserver < ActiveRecord::Observer
observe Project
def after_create(project)
project.members.each do |member|
ProjectMailer.deliver_notice(project, member)
end
end
end
7. Use Observer
After
72. 1. Isolating Seed Data
Before
class CreateRoles < ActiveRecord::Migration
def self.up
create_table "roles", :force => true do |t|
t.string :name
end
["admin", "author", "editor","account"].each do |name|
Role.create!(:name => name)
end
end
def self.down
drop_table "roles"
end
end
73. 1. Isolating Seed Data
After
# /db/seeds.rb (Rails 2.3.4)
["admin", "author", "editor","account"].each do |name|
Role.create!(:name => name)
end
rake db:seed
74. After
# /lib/tasks/dev.rake (before Rails 2.3.4)
namespace :dev do
desc "Setup seed data"
task :setup => :environment do
["admin", "author", "editor","account"].each do |name|
Role.create!(:name => name)
end
end
end
rake dev:setup
75. 2. Always add DB index
class CreateComments < ActiveRecord::Migration
def self.up
create_table "comments", :force => true do |t|
t.string :content
t.integer :post_id
t.integer :user_id
end
end
def self.down
drop_table "comments"
end
end
Before
76. 2. Always add DB index
class CreateComments < ActiveRecord::Migration
def self.up
create_table "comments", :force => true do |t|
t.string :content
t.integer :post_id
t.integer :user_id
end
add_index :comments, :post_id
add_index :comments, :user_id
end
def self.down
drop_table "comments"
end
end
After
78. 1. Use before_filter
class PostController < ApplicationController
def show
@post = current_user.posts.find(params[:id]
end
def edit
@post = current_user.posts.find(params[:id]
end
def update
@post = current_user.posts.find(params[:id]
@post.update_attributes(params[:post])
end
def destroy
@post = current_user.posts.find(params[:id]
@post.destroy
end
end
Before
79. 1. Use before_filter
class PostController < ApplicationController
before_filter :find_post, :only => [:show, :edit, :update, :destroy]
def update
@post.update_attributes(params[:post])
end
def destroy
@post.destroy
end
protected
def find_post
@post = current_user.posts.find(params[:id])
end
end
After
80. 2. DRY Controller
class PostController < ApplicationController
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id)
end
def new
@post = Post.new
end
def create
@post.create(params[:post]
redirect_to post_path(@post)
end
end
Before
def edit
@post = Post.find(params[:id)
end
def update
@post = Post.find(params[:id)
@post.update_attributes(params[:post])
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:id)
@post.destroy
redirect_to posts_path
end
82. After
2. DRY Controller
class PostController < InheritedResources::Base
# if you need customize redirect url
def create
create! do |success, failure|
seccess.html { redirect_to post_url(@post) }
failure.html { redirect_to root_url }
end
end
end
83. • You lose intent and readability
• Deviating from standards makes it harder
to work with other programmers
• Upgrading rails
DRY Controller Debate!!
小心走火入魔
from http://www.binarylogic.com/2009/10/06/discontinuing-resourcelogic/
86. 1. Move code into controller
<% @posts = Post.find(:all) %>
<% @posts.each do |post| %>
<%=h post.title %>
<%=h post.content %>
<% end %>
Before
class PostsController < ApplicationController
def index
@posts = Post.find(:all)
end
end
After
87. 2. Move code into model
<% if current_user && (current_user == @post.user ||
@post.editors.include?(current_user) %>
<%= link_to 'Edit this post', edit_post_url(@post) %>
<% end %>
<% if @post.editable_by?(current_user) %>
<%= link_to 'Edit this post', edit_post_url(@post) %>
<% end %>
class Post < ActiveRecord::Base
def ediable_by?(user)
user && ( user == self.user || self.editors.include?(user)
end
end
Before
After
88. 3. Move code into helper
<%= select_tag :state, options_for_select( [[t(:draft),"draft" ],
[t(:published),"published"]],
params[:default_state] ) %>
Before
After
<%= select_tag :state, options_for_post_state(params[:default_state]) %>
# /app/helpers/posts_helper.rb
def options_for_post_state(default_state)
options_for_select( [[t(:draft),"draft" ],[t(:published),"published"]],
default_state )
end
89. 4. Replace instance variable
with local variable
<%= render :partial => "sidebar" %>
<%= render :partial => "sidebar", :locals => { :post => @post } %>
Before
After
class Post < ApplicationController
def show
@post = Post.find(params[:id)
end
end
90. 5. Use Form Builder
<% form_for @post do |f| %>
<p>
<%= f.label :title, t("post.title") %> <br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :content %> <br>
<%= f.text_area :content, :size => '80x20' %>
</p>
<p>
<%= f.submit t("submit") %>
</p>
<% end %>
Before
91. 5. Use Form Builder
After
<% my_form_for @post do |f| %>
<%= f.text_field :title, :label => t("post.title") %>
<%= f.text_area :content, :size => '80x20',
:label => t("post.content") %>
<%= f.submit t("submit") %>
<% end %>
92. module ApplicationHelper
def my_form_for(*args, &block)
options = args.extract_options!.merge(:builder =>
LabeledFormBuilder)
form_for(*(args + [options]), &block)
end
end
class MyFormBuilder < ActionView::Helpers::FormBuilder
%w[text_field text_area].each do |method_name|
define_method(method_name) do |field_name, *args|
@template.content_tag(:p, field_label(field_name, *args) +
"<br />" + field_error(field_name) + super)
end
end
def submit(*args)
@template.content_tag(:p, super)
end
end
After
93. 6. Organize Helper files
# app/helpers/user_posts_helper.rb
# app/helpers/author_posts_helper.rb
# app/helpers/editor_posts_helper.rb
# app/helpers/admin_posts_helper.rb
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
end
# app/helpers/posts_helper.rb
Before
After
94. 7. Learn Rails Helpers
• Learn content_for and yield
• Learn how to pass block parameter in helper
• my slide about helper: http://www.slideshare.net/ihower/building-web-interface-on-rails
• Read Rails helpers source code
• /actionpack-x.y.z/action_view/helpers/*