Skip to content

Instantly share code, notes, and snippets.

View xab3r's full-sized avatar

Yevhen Nakonechnyi xab3r

  • Canada, Vancouver
View GitHub Profile

Пример рефакторинга с использованием транзакций

Опять рассмотрим tasks#create экшен.

В экшене 3 разных логики, которые выполняются последовательно:

  1. валидация данных - необходимый шаг;
  2. сохраниение таска - необходимый шаг, если какая-то ошибка, необходимо возвращать failed значение;
  3. отправка нотификаций - мы не хотим, что бы наша транзакия не выполнялась, если отправка нотификации не выполнится;

Поэтому напишем нашу транзакцию. Так же мы будем использовать Either монаду для возвращения статуса шага транзакции. Right для успешного, Left - не успешного:

@xab3r
xab3r / gems.rb
Last active October 28, 2017 20:30 — forked from Ptico/gems.rb
My default rails gemfile
source 'https://rubygems.org'
BUNDLE_RAILS_VERSION = '~> 4.2.4'
# Rails
gem 'railties', BUNDLE_RAILS_VERSION
gem 'activesupport', BUNDLE_RAILS_VERSION
gem 'actionpack', BUNDLE_RAILS_VERSION
gem 'actionmailer', BUNDLE_RAILS_VERSION
gem 'activejob', BUNDLE_RAILS_VERSION
@xab3r
xab3r / 0_reuse_code.js
Created April 1, 2017 14:31
Here are some things you can do with Gists in GistBox.
// Use Gists to store code you would like to remember later on
console.log(window); // log the "window" object to the console
module AuthHelper
def http_login
user = 'username'
pw = 'password'
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)
end
end
module AuthRequestHelper
#
class PagesController < ApplicationController
before_filter :login_required, :except => [ :show ]
# GET /pages
# GET /pages.xml
def index
@pages = Page.find(:all)
respond_to do |format|
format.html # index.html.erb

Render and Redirect

The normal controller/view flow is to display a view template corresponding to the current controller action, but sometimes we want to change that. We use render in a controller when we want to respond within the current request, and redirect_to when we want to spawn a new request.

Render

The render method is very overloaded in Rails. Most developers encounter it within the view template, using render :partial => 'form' or render @post.comments, but here we'll focus on usage within the controller.

:action

#Model
@user.should have(1).error_on(:username) # Checks whether there is an error in username
@user.errors[:username].should include("can't be blank") # check for the error message
#Rendering
response.should render_template(:index)
#Redirecting
response.should redirect_to(movies_path)

In Rails 3

NOTE: This post now lives (and kept up to date) on my blog: http://hakunin.com/rails3-load-paths

If you add a dir directly under app/

Do nothing. All files in this dir are eager loaded in production and lazy loaded in development by default.

If you add a dir under app/something/

# Permissions cheatsheet
`chmod [a]bcd`
* bit a — sticky:1/setgid:2/setuid:4 (optional, default: 0)
* bit b — owner | x:1/w:2/r:4 - xw:3/xr:5/wr:6/xwr:7
* bit c — group | x:1/w:2/r:4 - xw:3/xr:5/wr:6/xwr:7
* bit d — everyone | x:1/w:2/r:4 - xw:3/xr:5/wr:6/xwr:7
note: only file/dir owner can chmod it
=Navigating=
visit('/projects')
visit(post_comments_path(post))
=Clicking links and buttons=
click_link('id-of-link')
click_link('Link Text')
click_button('Save')
click('Link Text') # Click either a link or a button
click('Button Value')