Categories
Uncategorized

Ruby On Rails

A web development framework is a code library that provides developers with a time-saving solution – a time-consuming effort to create forms, tables, and menus on a website. Rails and Ruby on Rails are about providing developers with time-saving techniques for writing code. To ask you as a developer of Ruby and Rails, I have compiled a rails tutorial that allows you to learn from the best in the field.
The ability to quickly create a website allows you to see how theory is applied in practice. Although the terms Ruby and Ruby on Rails are often interchangeable, Ruby is Ruby – on – Rails because it is a keyboard library written in the Ruby programming language, which allows developers to quickly create websites and web apps. It is advisable to learn Ruby as a framework language, i.e. as an application language, rather than learning the language itself, because learning a framework allows you to make rapid progress from the start, i.e. you can quickly create a website that you and your friends can share with them.
Rails is based on a well-established software model, which is briefly called Model – View – Controller (MVC). Before we delve into the details of the “MVC” pattern in rails, one major fallacy that often happens is that you have to use rails to learn Ruby properly. Most people are introduced to Ruby by by using a framework language like Ruby-on-Rails or Ruby on Rails 2.0 to quickly create web pages.
If you have an idea and want to implement it quickly, the Rails framework is your – go framework. Building a project or product with Ruby on Rails is extremely fast and easy, and developers using it can build faster than teams using any other stack.
Ruby on Railsallows for a wide range of use cases, from web applications to web services, mobile apps and even web servers.
If you’re looking for a job as a web developer, joining a startup or just hitting a frontend framework (like Vue or React) and your web application is well received, Rails is your first choice. Whether for web development, web services, mobile applications or even web servers, it is a good choice for any type of application.
This varies depending on the company and its backend development requirements, but developers generally work on both web servers and database applications. Backend developers work with things that the user does not see happening on the server side, such as the database or web server.
To get a better understanding of what sets them apart from other programming skills and how to learn them, I spoke to a group of developers from Ruby on Rails. Rails is a web development framework, but there are actually a number of different versions of it, each with its own strengths and weaknesses. Basically Ruby – on – Rails itself is supposed to be a “web development framework” that gives its developers time – a way of writing code.
Ruby on Rails – Rails is a server-side web application framework written in Ruby under the MIT license. It is a model view controller (MVC) framework that provides a framework for developing web applications with a variety of features, such as the ability to provide models, views, controllers and an “MVC framework.”
Rails to facilitate and promote user interface design, user interaction and user communication between user and application.
Rails combines the Ruby programming language with HTML, CSS and JavaScript to create web applications that run on web servers. Later, this article will describe the web application in more detail and show you why you need a web development framework to build complex web pages. Rails running on a web server are considered front-end and the web browser as back-end, with the user interface and user interaction located in the backend.
This trend does not seem to be waning any time soon, and Ruby on Rails continues to be the go – a framework for managing all kinds of web projects. Since Rails is everything we covered #, we have put together a brief overview of the basics of Rails and how they can be used in web development before we get into the amazing possibilities that come with it. The framework is a combination of webserver, front end and backend, with a little HTML and CSS.
Ruby on Rails is based on a model view controller architecture (MVC), which means that the data is separated from the user interface and different views are provided for each data. The framework is equipped with many generation commands that allow you to automatically create the frame files needed for simple objects, including the front, back end and back end components of your web application. To develop web applications, you can use Ruby on Rails in a variety of ways: as a web server, front-end framework or backend framework.

Categories
Uncategorized

Creating your own WordPress plugin database migration framework

How to create a database migration framework for WordPress that automatically migrates changes to your plugin database structure.

So, how do you migrate changes to your database structure from one version to another (like you may know it from Ruby on Rails) when you are writing a WordPress plugin? Here’s one way to do it.

Let’s assume that the database migration should take place when the plugin is activated. Assuming your plugin is named myplugin, put this code in the myplugin.php file:

register_activation_hook(__FILE__, ‘myplugin_install’);
This makes WordPress execute the myplugin_install() method when the user activates your plugin.

Next, add this method:

function myplugin_install() {
myplugin_migrate();
}
And our migration method:

function myplugin_migrate() {
global $wpdb;

$migs = myplugin_migrations();

$current_migration = get_option(‘myplugin_current_migration’, 0);
$needed_migration = count($migs);

for ($i = $current_migration; $i < $needed_migration; $i++) { $mig = $migs[$i]; $wpdb->query($mig);
}

if ($current_migration == 0) {
add_option(‘myplugin_current_migration’, $needed_migration);
} else {
update_option(‘myplugin_current_migration’, $needed_migration);
}
}
What this does is that it runs through database statements (queries) returned from the myplugin_migrations() method. Let’s implement the actual migrations – add this method:

function myplugin_migrations() {
global $wpdb;

$migs = array();

// Create example table
$migs[] = ‘
CREATE TABLE ‘.$wpdb->prefix.’myplugin_examples (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (id)
)’;

// Add examples
$migs[] = “INSERT INTO “.$wpdb->prefix.”myplugin_examples SET name=’First example'”;
$migs[] = “INSERT INTO “.$wpdb->prefix.”myplugin_examples SET name=’Second example'”;

// Return the migrations
return $migs;
}
That would create an example table and insert some values.

Now imagine that two months later you need a description field in your examples table. What do you do? It’s as easy as adding one line of code to the migrations:

// Add description field to examples
$migs[] = “ALTER TABLE “.$wpdb->prefix.”myplugin_examples ADD description VARCHAR( 255 ) NOT NULL”;
Deactivate and activate the plugin, and you table now has an extra field. Easy as cake! 🙂

Share your thoughts, opinions, and suggestions below.

Categories
Uncategorized

Creating a public symlink using Capistrano

How to create a public symlink that’s shared between releases using Capistrano.

So, I have a folder containing static sitemap files for my site. These sitemaps are generated and saved in my public/sitemap folder. However, I want to keep these sitemap files between deployments.

What I need is a symlink from public/sitemap that’s pointing to shared/sitemap.

I use Capistrano for my deployments, so I need the following task (I renamed my sitemap namespace and folder to better reflect other needs you might have):

after “deploy:update_code”, “my_namespace:symlink”

namespace :my_namespace do
desc “Create symlink”
task :symlink do
run “rm -rf #{release_path}/public/my_folder”
run “mkdir -p #{shared_path}/my_folder”
run “ln -nfs #{shared_path}/my_folder #{release_path}/public/my_folder”
end
end
This will remove any existing public/my_folder folder (e.g. if it was deployed from your development repository), create the shared/my_folder folder (if it doesn’t exist), and at last create the symlink from public/my_folder to shared/my_folder.

As easy as that 🙂 Hope you can use it.

Categories
Uncategorized

Examples of Ruby on Rails

Basic set of examples to read if you want to learn Ruby on Rails.

When I want to learn a new programming language or framework, I usually first try to find some examples to look at. Many times I have found it hard to find a single page with some good examples on how a language works. Not a tutorial, just examples. Here is a basic set of examples I would find nice to read if I wanted to learn about the Ruby on Rails web application development framework. Find more resources for learning the framework at the bottom of the post.

New Rails project
In the shell:

$ rails new example_project
$ cd example_project
Models
In app/models/post.rb:

class Post < ActiveRecord::Base has_many :comments, :dependent => :destroy # post.comments with autodelete
validates_presence_of :title, :content
end
In app/models/comment.rb:

class Comment < ActiveRecord::Base belongs_to :post # comment.post validates_presence_of :text end Controllers In app/controllers/posts_controller.rb: class PostsController < ApplicationController def index @posts = Post.all end def show @post = Post.find(params[:id]) end def new @post = Post.new end def create @post = Post.new(params[:post]) if @post.save redirect_to @post, :notice => “The post was created successfully.”
else
render :new
end
end

def edit
@post = Post.find(params[:id])
end

def update
@post = Post.find(params[:id])

if @post.update_attributes(params[:post])
redirect_to @post, :notice => “The post was updated successfully.”
else
render :edit
end
end

def destroy
@post = Post.find(params[:id])
@post.destroy

redirect_to posts_path, :notice => “The post was deleted successfully.”
end
end
Views
In app/views/posts/index.html.erb:

All posts

    <% @posts.each do |post| %>

  • <%= link_to post.title, post %>
  • <% end %>

<%= link_to "New post", new_post_path %>
<%= link_to "Back to homepage", root_path %>

In app/views/posts/show.html.erb:

<%= @post.title %>

Created: <%= @post.created_at %>

<%= link_to "Delete post", @post, :method => :delete %>

<%= @post.content %>

Comments

<% @post.comments.each do |comment| %>

<%= comment.text %>

<% end %>

<%= link_to "Back to posts", posts_path %>
In app/views/posts/new.html.erb:

New post

<%= form_for @post do |f| %>

<%= f.label :title %>
<%= f.text_field :title %>

<%= f.label :content %>
<%= f.text_area :content %>

<%= f.submit "Create post" %>

<% end %>
View layouts
In app/views/layouts/application.html.erb:



Rails example


<% if flash[:notice] %>

<%= flash[:notice] %>

<% end %>
<%= yield %>


View partials
In app/views/shared/_example_partial.html.erb:

Content of example variable: <%= example_variable %>

In another view:

<%= render "shared/example_partial", :example_variable => “Example content” %>
Rendering other formats
In app/controllers/posts_controller.rb:

class PostsController < ApplicationController def index @posts = Post.all respond_to do |format| format.html # index.html.erb format.json { render :json => @posts }
end
end
end
In the browser:
http://localhost:3000/posts.json

Database migrations
In the shell:

$ rails generate model post title:string content:text
In db/migrate/20121228215855_create_posts.rb:

class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.string :title t.text :content t.timestamps end end end In the shell: $ rails generate model comment post_id:integer text:text In db/migrate/20121228220327_create_comments.rb: class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.integer :post_id t.text :text t.timestamps end add_index :comments, :post_id end end Then, in the shell: $ rake db:migrate Routing In config/routes.rb: ExampleProject::Application.routes.draw do resources :posts do # /posts, /posts/123, etc. => PostsController
resources :comments # /posts/123/comments, /posts/123/comments/345, etc. => CommentsController
end

match “contact” => “home#contact” # /contact => HomeController#contact

root :to => “home#index” # / => HomeController#index
end
Plugins
In Gemfile:

# To use jQuery
gem ‘jquery-rails’

# To use Jbuilder templates for JSON
gem ‘jbuilder’

# Deploy with Capistrano
gem ‘capistrano’
In the shell:

$ bundle install
Rails development server
In the shell:

$ rails server
To see posts:
http://localhost:3000/posts

To see a single post:
http://localhost:3000/posts/123

To edit a post:
http://localhost:3000/posts/123/edit

Categories
Uncategorized

Sublime Text: Convert Ruby 1.8 to 1.9 style hash syntax

How to automatically replace and convert Ruby 1.8 to 1.9 style hash syntax using Sublime Text without any plugins or gems.

Ruby 1.9 and 2.0 has a new hash syntax. In Ruby 1.8 it was:

hash = { :one => “first value”, :two => “second value” }
In Ruby 1.9 and 2.0, this can now be written as:

hash = { one: “first value”, two: “second value” }
Saving three characters per key.

If you’re using Sublime Text, it’s really easy to do this conversion automatically.

Here’s how to do it – use it at your own risk, and take a backup first:

Go to Find → Find in Files…
Enable Regular expressions – make sure the .* button is activated
In the Find box: :([a-z_\d]+) =>
In the Replace box: \1:
Click the Replace button. This will replace matches in all of your files in Sublime Text. It will also go through non-Ruby files so it might be a good idea to set a Where file pattern to *.rb or *.html.erb. As I said, use at your own risk, and take a backup first.

Categories
Uncategorized

Gracefully reindex Sunspot Solr without dropping indexes

How to reindex your Sunspot Solr models without dropping the entire index first.

If you’re using the Ruby on Rails Sunspot gem for searching your models, running rake sunspot:solr:reindex will drop your entire index before reindexing the models.

If you want to reindex the models gracefully without dropping the indexes first, you can put this task in lib/tasks/sunspot_tasks.rake:

# lib/tasks/sunspot_tasks.rake

namespace :sunspot do
task :reindex_gracefully => :environment do
Dir.glob(Rails.root.join(‘app/models/**/*.rb’)).each { |path| require path }
sunspot_models = Sunspot.searchable

index_options = { :batch_commit => false }

begin
require ‘progress_bar’
total_documents = sunspot_models.map { | m | m.count }.sum
index_options[:progress_bar] = ProgressBar.new(total_documents)
rescue LoadError => e
$stdout.puts “Skipping progress bar: for progress reporting, add gem ‘progress_bar’ to your Gemfile”
rescue Exception => e
$stderr.puts “Error using progress bar: #{e.message}”
end

sunspot_models.each do |model|
model.solr_index index_options
end
end
end
The task is a simplified, slightly modified version of Sunspot’s built-in sunspot:reindex task.

Then run:

$ rake sunspot:reindex_gracefully
Now you can reindex without dropping the index. Enjoy 🙂

Categories
Uncategorized

Fixing “You have already activated rake 10.1.0, but your Gemfile requires rake 10.0.0″

How to fix the “Gem::LoadError: You have already activated rake 10.1.0, but your Gemfile requires rake 10.0.0. Using bundle exec may solve this.” error by updating the gem.

Just a quick note for searchers.
Maybe you got this error:

Gem::LoadError: You have already activated rake 10.1.0, but your Gemfile requires rake 10.0.0. Using bundle exec may solve this.
~/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.4/lib/bundler/runtime.rb:33:in `block in setup’
~/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.4/lib/bundler/runtime.rb:19:in `setup’
~/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.4/lib/bundler.rb:120:in `setup’
~/.rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.4/lib/bundler/setup.rb:17:in `
~/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:110:in `require’
It’s easy to fix. Just run:

$ bundle update rake # or whatever your gem is called
If this does not work, you can use bundle exec as the error says.