background preloader

Ruby

Facebook Twitter

Delete model and migration file rails 4. Simple Authentication in Rail 4 Using Bcrypt. Simple Authentication with Bcrypt This tutorial is for adding authentication to a vanilla Ruby on Rails app using Bcrypt and has_secure_password. The steps below are based on Ryan Bates's approach from Railscast #250 Authentication from Scratch (revised). You can see the final source code here: repo.

I began with a stock rails app using rails new gif_vault Steps Create a user model with a name, email and password_digest (all strings) by entering the following command into the command line: rails generate model user name email password_digest. Things Missing Adding flash messages would be simple and provide feedback to the user if things go wrong. Ruby on rails - has_secure_password is saving password in plain text.

Creating a Simple Search in Rails 4 | Koren Leslie Cohen. Say you have a blog and you want the user to be able to search your posts, you will need to add methods to both your posts controller and post model, and create a corresponding search form. 1. Posts Controller In your posts_controller.rb file, add the following to your index method: def index @posts = Post.all if params[:search] @posts = Post.search(params[:search]).order("created_at DESC") else @posts = Post.all.order('created_at DESC') end end 2. In your post.rb file, add the following method: def self.search(search) where("name LIKE ? " You can choose the fields you’d like your search form to query.

Note: this will work in development with SQLite. 3. In your views/posts/index.html.erb (or wherever you’d like to place the search form), add the following simple form: <%= form_tag(posts_path, :method => "get", id: "search-form") do %><%= text_field_tag :search, params[:search], placeholder: "Search Posts" %><%= submit_tag "Search" %><% end %> 4. <% if @posts.present? Koren Leslie Cohen. Command Pattern Tutorial with Java Examples - DZone Java. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround. Today's pattern is the Command, which allows the requester of a particular action to be decoupled from the object that performs the action.

Where the Chain of Responsibility pattern forwarded requests along a chain, the Command pattern forwards the request to a specific module. Command in the Real World One example of the command pattern being executed in the real world is the idea of a table order at a restaurant: the waiter takes the order, which is a command from the customer.This order is then queued for the kitchen staff. The waiter tells the chef that the a new order has come in, and the chef has enough information to cook the meal.

Design Patterns RefcardFor a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. The Command Pattern So what does this mean in a class diagram? When Would I Use This Pattern? So How Does It Work In Java? Chapter 4. Structural Patterns: Adapter and Façade. This chapter is excerpted from C# 3.0 Design Patterns: Use the Power of C# 3.0 to Solve Real-World Problems by Judith Bishop, published by O'Reilly Media The main pattern we will consider in this chapter is the Adapter pattern. It is a versatile pattern that joins together types that were not designed to work with each other.

It is one of those patterns that comes in useful when dealing with legacy code-i.e., code that was written a while ago and to which one might not have access. There are different kinds of adapters, including class, object, two-way, and pluggable. We'll explore the differences here. Adapter Pattern Role The Adapter pattern enables a system to use classes whose interfaces don't quite match its requirements. Toolkits also need adapters. Illustration Our illustration of the Adapter pattern is a very real one-it involves hardware instruction sets, not input/output. Figure 4.1. Thus, the Accelerate framework is an example of the Adapter pattern. Design Figure 4.2. ITarget Use. Railsでacts-as-taggable-onを使ってタグ管理を行う - Rails Webook. Flickr: cambodia4kidsorg's Photostream acts-as-taggable-onはタグの追加、削除、関連するオブジェクトの取得、タグクラウドなどのタグを管理するためのgemです。 今回は、Railsでacts-as-taggable-onでタグ管理を行う方法について説明します。 動作確認 Ruby 2.2.0Rails 4.2.0acts-as-taggable-on 3.4.4 目次 1. acts-as-taggable-onのインストール Gemfileに追加します。

Gem 'acts-as-taggable-on', '~> 3.4' バンドルを実行します。 Bunlde acts-as-taggable-onで必要なテーブルを作成します。 Bin/rake acts_as_taggable_on_engine:install:migrations bin/rake db:migrate 2. acts-as-taggable-onの基本的な使い方 モデルファイルにacts_as_taggable_onを追加します。 Class Post < ActiveRecord::Base acts_as_taggable_on :labels acts_as_taggable end 上記のように設定することで、以下の2つのメソッドを利用することができます。 Post.label_list post.tag_list 次のようにして、タグの追加、取得、設定、削除ができます。

Post.tag_list.add("programming") post.tag_list.add("tips", "hardware") post.save post.label_list post.tag_list post.tag_list = ["programming", "tips"] post.tag_list post.tag_list.remove("programming") post.tag_list.clear 「最も使われているタグ」と「最も使われていないタグ」を取得できます。 Tagged_withメソッドで、特定のタグでPostを検索するができます。 Find_related_skillsメソッドで、同じタグを持ったPostを検索することができます。 以上です。 Php/regex - Extract proper nouns from text. Rails migration does not change schema.rb. Get categories from Feed Rss with ruby. ActiveRecord::FinderMethods. Methods exists? Constants Instance Public methods exists? (conditions = :none) Link Returns true if a record exists in the table that matches the id or conditions given, or false otherwise.

For more information about specifying conditions as a hash or array, see the Conditions section in the introduction to ActiveRecord::Base. Note: You can't pass in a condition as a string (like name = 'Jamie'), since it would be sanitized and then queried against the primary key column, like id = 'name = \'Jamie\''. Person.exists? Def exists? Find the fifth record. Same as fifth but raises ActiveRecord::RecordNotFound if no record is found.

Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). ActiveRecord::RecordNotFound will be raised if one or more ids are not found. NOTE: The returned records may not be in the same order as the ids you provide since database rows are unordered. Find with lock Variations of find Alternatives for find def find_by!

Rails 3. Factory Method Design Pattern. Intent Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.Defining a "virtual" constructor.The new operator considered harmful. Problem A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation. Discussion Factory Method is to creating objects as Template Method is to implementing an algorithm. A superclass specifies all standard and generic behavior (using pure virtual "placeholders" for creation steps), and then delegates the creation details to subclasses that are supplied by the client. Factory Method makes a design more customizable and only a little more complicated.

Factory Method is similar to Abstract Factory but without the emphasis on families. Structure The client is totally decoupled from the implementation details of derived classes. Part 3: Keeping Our Balance | Ruby Objects and Classes | Treehouse. Factory methods in Ruby. Design Patterns in Ruby: Observer, Singleton. I am going to be posting a few articles related to Software Design Patterns and how they are applicable to Ruby. The first two patterns that will be covered are the Observer Pattern and the Singleton Pattern. Observer Pattern If you are not familiar with this pattern, no worries, it is basically a mechanism for one object to inform other ‘interested’ objects when its state changes. To be a little more descriptive, here is a direct quote from Wikipedia: The observer pattern (aka. The Observable module in the Ruby standard library provides the mechanism necessary for us to implement this pattern, and it is fairly easy to use.

The Planning In order to use this pattern, we first need to come up with a scenario. The Basic Structure The first thing that we are going to do is create a basic structure for our Notifier class that will act as an observer. Let us start by putting together a simple Notifier class: That is as simple as it gets. Fixing the Notifier Class Putting It All Together Planning. Ruby on rails - Getting attribute's value in Nokogiri to extract link URLs. Ruby on rails - Reset the database (purge all), then seed a database. Ruby - Removing a model in rails (reverse of "rails g model Title...")

Set Up Cron Jobs in Rails. Recently I came to a situation where I need to take an action based on time. For example, a web application helps organizing an event and 48 hours before its scheduled time, it'll send out a reminder email to all attendees. It doesn't trigger by view, only time. Setting up a cron job or a delayed job can both achieve the goal. Let's look at cron job. In Rails, there are many gems available for scheduling. WheneverRufus schedulerResque schedulerClockwork Whenever Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs. How to use? In Rails 4, you can put the gem in Gemfile and run bundle install.

Every 1.day, :at=>'5:00am' do your script end You could do every 2.hours, every :sunday or even use cron syntax every '0 0 2 * *' Then whenever translate that into crontab job by issuing: whenever --update-crontab my_cron_name my_cron_name is just a name for your cronjob that can be updated easily later on. The process is pretty clear and straighforward. Rufus scheduler. Ruby on rails - Getting attribute's value in Nokogiri to extract link URLs. Ruby on rails - How to bypass SSL certificate verification in open-uri? A dirty one-liner that do steps of.

Download a cacert.pem for RailsInstaller. Ruby on rails - How to solve "certificate verify failed" on Windows? Personal Weather - hungry academy. Introduction Interacting with remote APIs can be one of the most entertaining parts of programming. As a novice programmer, you can immediately enhance your application through simple calls to external services. There are thousands of APIs you can use to display and interact with remote data. The possibilities are pretty much endless!

Below, we’re going to walk through what would go into building a personal weather site. You could easily extend this into a homemade personal dashboard - for example: include custom news, personal recommendations from Etsy, and your friend’s most recent tweets. Personal Weather Application: Getting Started Wunderground.com provides weather forecasts nationwide based on zip code lookup. Step 1: API Key Sign up for an API key. Step 2: Determine What Data You Want Check out the API documentation.

Wunderground’s API query format is as follows: Step 3: Building the Basic Application From the command line: Parsing HTML with Nokogiri. Nokogiri The Nokogiri gem is a fantastic library that serves virtually all of our HTML scraping needs. Once you have it installed, you will likely use it for the remainder of your web-crawling career. Installing Nokogiri Unfortunately, it can be a pain to install because it has various other dependences, libxml2 among them, that may or may not have been correctly installed on your system. Follow the official Nokogiri installation guide here.

Hopefully, this step is as painless as typing gem install nokogiri. For the remainder of this section, assume that the first two lines of every script are: require 'rubygems'require 'nokogiri' Opening a page with Nokogiri and open-uri Passing the contents of a webpage to the Nokogiri parser is not much different than opening a regular textfile. If the webpage is stored as a file on your hard drive, you can pass it in like so: page = Nokogiri::HTML(open("index.html")) puts page.class # => Nokogiri::HTML::Document The open-uri module Using rest-client id class.

Regression. Description Regression analysis is a statistical method used to describe the relationship between two variables and to predict one variable from another (if you know one variable, then how well can you predict a second variable?). Whereas for correlation the two variables need to have a Normal distribution, in regression analysis only the dependent variable Y should have a Normal distribution. The variable X does not need to be a random sample with a Normal distribution (the values for X can be chosen by the experimenter).

However, the variability of Y should be the same for each value of X. Required input When you select Regression in the menu, the following box appears on the screen: Variables Variable Y and Variable X: select the dependent and independent variables Y and X. Regression equation By default the option Include constant in equation is selected. MedCalc offers a choice of 5 different regression equations: where X represents the independent variable and Y the dependent variable. If you’re using to_json, you’re doing it wrong | CodePath. At Miso, we have been very busy in the last few months building out a large number of public APIs for our Developer Platform. In a short time, we have already seen early versions of applications built on our platform for Chrome, Windows Mobile 7, Blackberry, Playbook, XBMC among others. This has been very exciting to see the community embrace our platform and leverage our data to power additional services or bring our service to a new group of users.

In this post, we will discuss how we started out building our APIs using Rails and ‘to_json’, why we became frustrated with that approach and how we ended up building our own library for API generation. Our public APIs are designed to be unsurprising and intuitive for a developer. We chose OAuth 1.0a (soon to support OAuth 2) because this is already familiar to developers and there is rich library support across languages for this authentication strategy. Rails ‘to_json’ API generation The unravelling of ‘to_json’ begins Stay Tuned. Json - How to override to_json in Rails? Json - How to override to_json in Rails? Rails Models - Association, Creation. Model view controller - How to create Categories in Rails. Rails 3: Multiple Select with has_many through associations. Implementing Categories in Ruby on Rails the easy way. We’ve been working with Ruby on Rails for about 20 days now, and it is honestly the most efficient and secure framework we’ve ever come across.

The learning curve was a bit steep in the beginning, but we overcame that with the huge community support and tutorials available for ROR. We’re actually quite proud that we built a product with ROR having absolutely no experience in it. We did it! And so can you :) One module I was stuck with for quite some time was building hierarchies or categories. Okay. With categories, you need to select one model which behaves as your category and “has many” products and a product model that “belongs to” a single category. If you haven’t done so already, create a scaffold for Category and Product. Rails g scaffold product name:string price:string category_id and, rails g scaffold category name:string desc:text Category_id column in the Product model acts a foreign key between Product and Category. Then do a, Now you’ve created your two models.

Understanding Rails model view controller (MVC) | Codelearn Ruby on Rails Tutorial. Understanding Rails model view controller (MVC) | Codelearn Ruby on Rails Tutorial Module 1 - Lesson 5 In the last lesson - Adding pages from Rails controller - we created Pages controller with two actions - home and about. In this lesson, we will dive deeper into the Rails routes, Models, Views and Controller; also referred as Rails MVC architecture. The image below shows how Rails process an incoming URL. Figure: Interactions between Router --> Controller --> View User types a URL, lets say Now we will analyze what happens once the request reaches Pages controller, home action.

Class PagesController < ApplicationController def home end def about end end Each action fetches the view file associated with it, populate it with data (if any) and sends it to the browser. A quick recap :- Figure: Alternate view of Rails control flow. Ruby on Rails 實戰聖經. TypeError: 对象不支持此属性或方法 |Gemfile.lock 里的 coffee-script-source (1.9.1) 换成 coffee-script-source (1.8.0),然后重新bundle install. Gem 2.0.3 Unable to download data from - ... bad ecpoint · Issue #515 · rubygems/rubygems.

Ruby on rails - Error running gem install on Windows 7 64 bit. DevKit及rails的安装 - 萌萌的It人 www.itmmd.com. Statistic 2 - Exponential Regression Model. Statistics 2 - Logarithmic Regression Model. Normal Distribution. Polynomial Regression Data Fit. 多项式回归分析的例子_百度文库. 多项式回归分析_百度文库. Rubular: a Ruby regular expression editor and tester. Linear regression. Ruby: Ignore header line when parsing CSV file at Mark Needham.

使用NppExec插件在NotePad++下运行Ruby程序 - Zhu Lida's Private Bathtub. Regression. Polynomial Regression. Multiple_regression. How can I do standard deviation in Ruby?