text
stringlengths
10
2.61M
module Ricer::Plugins::Convert class Gunzip < Ricer::Plugin trigger_is :gunzip has_usage '<..text..>' def execute(text) begin text.force_encoding('binary') z = Zlib::Inflate.new reply = zstream.inflate(text) ensure z.finish z.close end end ...
class MessagesController < ApplicationController before_filter :require_user def new @message = Message.new end def create @message = Message.new(message_params) @message.account = @current_user.account addressee_account = find_existing_account(params[:message][:addressees_attributes][0][:url...
#!/usr/bin/env ruby # Copyright (c) 2013 Holger Amann <holger@sauspiel.de> # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitatio...
namespace :check do desc "Send a primary email for socail login users to reset their passwors based on new signup feature" task send_signup_notifications: :environment do subject = '“Important - your email login in Check”' User.where.not(email: '').find_each do |u| unless u.encrypted_password? ...
class Conf attr_reader :name, :tickets, :flights attr_accessor :popularity def initialize(name, tickets, flights) @name = name.downcase @tickets = tickets @flights = flights @popularity = 0 end def tickets? tickets > 0 end def flights? flights > 0 end def attend(app) ra...
class AdminController < ApplicationController before_action :authorized? def index # Static links end private def authorized? redirect_to root_path unless admin? end end
class FixColumnName < ActiveRecord::Migration def change rename_column :comments, :blog_id, :post_id end end
class Tag < ApplicationRecord validates :name, presence: true, length: { maximum: 100 } has_many :tag_post, dependent: :destroy has_many :post, through: :tag_post end
# == Schema Information # # Table name: subreleases # # id :integer not null, primary key # release_id :integer indexed, indexed => [subrelease_id] # subrelease_id :integer indexed => [release_id], indexed # created_at :datetime not null # updated_at :datetime...
Vagrant.configure("2") do |config| config.vm.box = "centos/7" config.vbguest.auto_update = false config.vm.box_check_update = false config.vm.synced_folder ".", "/vagrant", disabled: true # Gitea gitea config.vm.define "gitea" do |gitea| gitea.vm.network "private_network", ip: "192.168.4.11" gitea...
class RemoveStartAtFromOrderItems < ActiveRecord::Migration def change remove_column :order_items, :start_at end end
class PortfolioCoinsController < BaseController attr_reader :portfolio_coin before_action :authenticated? before_action :set_portfolio_coin, only: [:update, :destroy] def index refresh_market_coins(portfolio_coins) render json: portfolio_coins, each_serializer: PortfolioCoinSerializer end def c...
class ChangeShowsTable < ActiveRecord::Migration def change remove_column :shows, :latest_episode remove_column :shows, :next_episode add_column :shows, :last_title, :string add_column :shows, :last_airdate, :date add_column :shows, :last_episode, :string add_column :shows, :next_title, :strin...
require "rails_helper" RSpec.describe Category, type: :model do context "associations" do it {is_expected.to have_many(:news_leases)} it {is_expected.to have_many(:news_need_rents)} end end
require 'rails_helper' describe Slugable do let(:dummy_metaclass) { Class.new { include Slugable } } let(:instance) { dummy_metaclass.new } it "returns correctly slugified text" do text = "This is a rails 5 text" expect(instance.slugify(text)).to eq "this-is-a-rails-5-text" end it "returns correctl...
# Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) require 'rake' require 'rsolr' Lovelyromcoms::Application.load_tasks desc "start mongo and solr" ...
# encoding: utf-8 # copyright: 2016, @username-is-already-taken2 # copyright: 2016, @cdbeard2016 # license: All rights reserved title 'Example Controls to test windows_task resource' describe windows_task('\Microsoft\Windows\AppID\PolicyConverter') do its('logon_mode') { should eq 'Interactive/Background' } its('...
# require_relative "../../spec/spec_helper" # # RSpec.describe 'Check Yahoo Page' do # # before(:example) do # browser_setup(browser_version) # end # # after(:example) do |example| # capture_screenshot_on_failure(example) # end # # it "Check Yahoo text - True" do |example| # log_start_test("#{exam...
# frozen_string_literal: true # inventory class Inventory < ApplicationRecord belongs_to :ingredient belongs_to :ingredient_type scope :from_year, ->(date) { where(datetime: date.beginning_of_year..date.end_of_year).order(price: :desc) } scope :from_last_three_months, ->(date) { where(datetime: 2.months.ago.b...
class People < ApplicationRecord def self.all page = 0, per_page = 25 url = ENV['SALESLOFT_BASE_URL'] + '/v2/people.json' headers = { 'Authorization' => "Bearer #{ENV['SALESLOFT_API_KEY']}" } query_params = { 'per_page' => per_page, 'include_paging_counts' => true, 'page' => page } ...
class InstitutionsController < ApplicationController before_action :authenticate_user! def index @submission = Submission.find_by_user_id(current_user.id) if @submission @institutions = Institution.where(:submission_id => @submission.id) else redirect_to dashboard_home_path, :notice => "Ple...
require 'spec_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold ...
require 'test_helper' class ControlpnyntsControllerTest < ActionDispatch::IntegrationTest setup do @controlpnynt = controlpnynts(:one) end test "should get index" do get controlpnynts_url assert_response :success end test "should get new" do get new_controlpnynt_url assert_response :suc...
FactoryGirl.define do factory :course do name description subscribe_state :allowed end end
FactoryGirl.define do factory(:image) do description 'A picture' photo Rack::Test::UploadedFile.new("#{Rails.root}/spec/fixtures/images/wolv.jpg", "image/jpg") # photo_file_name {'spicoli.jpg'} # photo_content_type {'spicoli.jpg'} # photo_file_size {1024} end end
require "spec_helper" describe Paperclip::Storage::Ftp::Server do let(:server) { Paperclip::Storage::Ftp::Server.new } context "initialize" do it "accepts options to initialize attributes" do options = { :host => "ftp.example.com", :user => "user", :password => "password"...
FactoryBot.define do factory :pessoa do nome { FFaker::NameBR.first_name } sobrenome { FFaker::NameBR.last_name } documento { FFaker::IdentificationBR.cpf } email { FFaker::Internet.email } data_nascimento { FFaker::Time.date-FFaker::Random.rand(18..90).year } end end
require_relative("./db/sql_runner") require_relative("./star") require_relative("./casting") class Movie attr_reader :id attr_accessor :title, :genre, :rating def initialize(new_movie) @id = new_movie['id'].to_i if new_movie['id'] @title = new_movie['title'] @genre = new_movie['genre'] @rating ...
class LoginotesController < ApplicationController # before_action :logged_in_user, only: [:create] def new end def create @truck = Truck.find(params[:loginote][:truck_id]) @loginote = @truck.loginotes.build(loginote_params) if @loginote.save flash[:success] = "Loginote created" redirect_to ...
# # Cookbook Name:: IBM-IHS # Recipe:: default # # Copyright 2015, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # # ibm_ihs1 = node['ibm-ihs']['package1'] ibm_ihs2 = node['ibm-ihs']['package2'] ibm_ihs3 = node['ibm-ihs']['package3'] ibm_ihs_extract = node['ibm-ihs']['extract-dir'] ibm_ihs_bin = node[...
# frozen_string_literal: true RSpec.describe JwtAuth do describe '.auth_credentials' do context 'when token' do it 'should add user details to headers' do user = User.find_by_email ENV['ADMIN_EMAIL'] scopes = attributes_for(:permission, role: 'admin')[:permissions] token = attribute...
class AddRatesToReview < ActiveRecord::Migration def change add_column :reviews, :rate_1, :integer, default: 0 add_column :reviews, :rate_2, :integer, default: 0 add_column :reviews, :rate_3, :integer, default: 0 add_column :reviews, :rate_4, :integer, default: 0 add_column :reviews, :total_rating...
class CreateRecords < ActiveRecord::Migration def change create_table :records do |t| t.date :exam_date t.references :physician, index: true, foreign_key: true t.references :patient, index: true, foreign_key: true t.float :height t.float :weight t.integer :pulse t.integer...
namespace :heroku do desc 'restarts all the heroku dynos so we can control when they restart' task :restart do Heroku::API.new(username: ENV['HEROKU_USERNAME'], password: ENV['HEROKU_PASSWORD']).post_ps_restart(ENV['HEROKU_APP_NAME']) end end
module Events class NoteOnWorkspaceDataset < Note has_targets :dataset, :workspace has_activities :actor, :dataset, :workspace include_shared_search_fields(:dataset) end end
class CreateBrokerInfos < ActiveRecord::Migration def up create_table :broker_infos do |t| t.references :user, index: true t.float :lead_rate, default: 1 t.float :discount, default: 0 t.datetime :updated_at end end end
#!/usr/bin/env ruby lib_dir = File.expand_path('../../lib', __FILE__) $LOAD_PATH << lib_dir unless $LOAD_PATH.include?(lib_dir) require 'ept' require 'optparse' def usage $stderr.puts "USAGE: #{$0} verify FILENAME" exit 1 end command = ARGV.shift case command when "verify" options = {silent: false} Op...
Rails.application.routes.draw do mount GithubOnRails::Engine => "/github_on_rails" end
require_relative '../test_helper' class CommentTest < TestCase def setup 3.times.each do |i| Factory(:user) end User.first.boards.create!(name: "stop", active: true, description: "nothing") User.first.boards.create!(name: "start", active: true, description: "nothing") User.first.posts.creat...
# frozen_string_literal: true require 'gtk2' require_relative '../utils' require 'mui/gtk_extension' require 'mui/gtk_contextmenu' # CRUDなリストビューを簡単に実現するためのクラス class Gtk::CompatListView < Gtk::TreeView extend Memoist attr_accessor :dialog_title type_register def initialize super() initialize_model ...
require_relative '../../../src/conta.rb' # Pre-condition Given(/^I have an origin account$/) do |table| @saldo_inicial_joao = table.rows_hash['balance'].to_i @valor_transf = table.rows_hash['transfer_value'].to_i @conta_joao = Conta.new('JoaoOrigin') @conta_joao.deposita(@saldo_inicial_joao) end Given(/^I ha...
require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper') describe QuotientCube::Tree::Base do describe "with the store, product, season data set" do before(:each) do @table = Table.new( :column_names => [ 'store', 'product', 'season', 'sales' ], :data => [ ['...
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' class DefineMethodSpecClass end describe "Module#define_method when given an UnboundMethod" do it "correctly passes given arguments to the new method" do klass = Class.new do def test_method(arg1, ar...
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
class Marker < ApplicationRecord belongs_to :user belongs_to :post scope :bookmarks, -> { where(type_of_maker: "BOOKMARK") } scope :reported, -> { where(type_of_maker: "REPORTED") } validates :user_id, uniqueness: { scope: [:post_id]} end
#!/run/nodectl/nodectl script # Can be used to process transactions for a given node. All transactions are # considered as NoOp and thus always succeed. Can be used to temporarily bypass # offline node, however with consequences -- since the transactions are not # executed, the state of the database will not correspond...
require 'rails_helper' RSpec.describe 'お気に入り登録機能', type: :request do let(:user) { create(:user) } let!(:tweet) { create(:tweet, user: user) } context 'お気に入り登録処理' do context 'ログインしている場合' do before do sign_in user end it 'Tweetのお気に入り登録ができること' do expect { post "/ap...
class StudentRepprovedCourseSubject < ActiveRecord::Base self.table_name = "student_repproved_course_subject" belongs_to :course_subject_student has_many :student_examination_repproved_subjects end
class Book < ActiveFedora::Base has_metadata name: "properties", type: ActiveFedora::SimpleDatastream do |m| m.field('title') end end
json.array!(@mailing_lists) do |mailing_list| json.extract! mailing_list, :id, :name json.url mailing_list_url(mailing_list, format: :json) end
class AddBeerStyleReference < ActiveRecord::Migration[5.2] def change add_reference :beers, :styles, index: true reversible do Style.all.each do |style| Beer.where(old_style: style.name).each do |beer| beer.styles_id = style.id beer.save! end end end end ...
shared_examples 'total count pagination param' do it 'responds with the total_count passed to render_paginated, overwrites the real total_count' do expect(response_body(response)['total_count']).to( be Constants::DEFAULT_TOTAL_COUNT[:total_count] ) expect(response_body(response)['total_count']).not_...
=begin rdoc -------------------------------------------------------------------------------- Run rapper against all eligible files in a directory tree, compiling a list of the syntax errors in the files. -------------------------------------------------------------------------------- Usage: ld4l_scan_directory_tree ...
require 'rails_helper' RSpec.describe Comment, type: :model do context 'a comment belongs to a user' do it {should belong_to(:user)} end context 'a comment belongs to a post' do it {should belong_to(:post)} end end
class RemoveSeenIdFromMovie < ActiveRecord::Migration[5.1] def change remove_column :movies, :seen_id end end
class AddHealthToDeploymentTargetsMetadata < ActiveRecord::Migration def change add_column :deployment_target_metadata, :adapter_is_healthy, :boolean end end
FactoryBot.define do factory :item do name { Faker::Food.fruits } price { rand(0..99_999_999) } count { rand(0..99) } association :shop end end
class BlogsController < ApplicationController def index @blogs = Blog.all end def new @blog = Blog.new end def create blog = Blog.new(blog_params) blog.user_id = current_user.id if blog.save redirect_to "/" else render "blogs/new" end end def show @blog = Blog.find(params[:id]) @...
class Meow < ActiveRecord::Base def sound_type if self.cat "cat" else "human" end end end
# == Schema Information # # Table name: pages # # id :integer not null, primary key # slug :string(255) not null # title :string(255) not null # body :text # account_id :integer # parent_id :integer # created_at :datetime not null # updated_at :datetime ...
## # Simple class to hold a collection of search result data. # class GoogleCustomSearch::ResultSet include Kaminari::ConfigurationMethods::ClassMethods attr_reader :time, :total, :pages, :suggestion, :labels attr_internal_accessor :limit_value, :offset_value alias :total_count :total def self.create(...
# A triangle is classified as follows: # right One angle of the triangle is a right angle (90 degrees) # acute All 3 angles of the triangle are less than 90 degrees # obtuse One angle is greater than 90 degrees. # To be a valid triangle, the sum of the angles must be exactly 180 degrees, # and all angles must be great...
class Board attr_accessor :x, :y, :parent, :children def initialize(x, y, parent=nil) @x = x @y = y @parent = parent @children = [] end def possible_children candidates = [] candidates << [@x+1,@y+2] candidates << [@x+1,@y-2] candidates << [@x-1,@y+2] candidates << [@x-1,@y-2] candidates << [@...
class MovesController < ApplicationController before_action :set_move, only: [:show, :edit, :update, :destroy] # GET /moves/1 # GET /moves/1.json def show end def update respond_to do |format| if @move.update(move_params) format.html { redirect_to root_path, notice: 'move was successfull...
Rails.application.routes.draw do get 'password_resets/new' get 'password_resets/edit' get '/signup', to:'users#new' post '/signup', to:'users#create' get '/login', to:'sessions#new' post '/login', to:'sessions#create' # 画像データの取得 get '/show_image', to: 'application#show_image' delete '/logout'...
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundat...
# coding: utf-8 require 'taggable' class Content include Mongoid::Document include Mongoid::Timestamps include Mongoid::Commentable # include Mongoid::TaggableWithContext # include Mongoid::TaggableWithContext::AggregationStrategy::MapReduce # include Mongoid::TaggableWithContext::AggregationStrategy::Re...
class EssayStyleDetail include RailsHelpers def self.build(controller) issue = IssueQuery.find(controller.params.require(:issue_id)) essay_style = EssayStyleQuery.find(controller.params.require(:id)) self.new(issue, essay_style) end delegate :friendly_id, :title, to: :essay_style delegate :yea...
require_relative '../../../puppet_x/century_link/clc' require_relative '../../../puppet_x/century_link/prefetch_error' Puppet::Type.type(:clc_group).provide(:v2, parent: PuppetX::CenturyLink::Clc) do mk_resource_methods read_only(:id, :servers_count) IGNORE_GROUP_NAMES = ['Archive', 'Templates'] def self.in...
class Service < ApplicationRecord belongs_to :branch has_one :company, through: :branch has_one :region, through: :branch validates :branch, :name, :price_cents, :duration_minutes, presence: true validates :price_cents, :duration_minutes, numericality: true validates :name, uniqueness: { scope: :branch } ...
class SvnRepo < ActiveRecord::Base inherits_from :repo, methods: true belongs_to :project, class_name: SvnProject end
require_relative 'image' class Menu attr_reader :image def show_menu system('clear') loop do print '> ' process(STDIN.gets.chomp) end end def process(input) begin case input when /^I\s+\d+\s+\d+$/ new_image(*parse(input)) when /^C$/ @image.cle...
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :init before_filter :handle_cookies def handle_cookies # Do whatever it is you want to do with ...
#Questions #1. How do I construct proper password confirmation and validation? #2. How to create proper views/errors for when a signup field is left blank or a password is incorrect class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use ...
def no_dupes?(arr) singles = [] until arr.empty? ele = arr.shift if arr.include?(ele) arr.delete(ele) else singles << ele end end singles end # Write a method no_dupes?(arr) that accepts an array as an arg and returns an new array containing the e...
class ReportsController < ApplicationController def viewofficers if session[:logged_in].nil? redirect_to home_404_path return end @OFFICERS = Officer.order(Order: :asc) reports = Report.order(Officer_ID: :asc) statuses = Status.all @REPORTS = [] for i in reports for ...
#!/usr/bin/env ruby require 'test/unit' require 'fileutils' require 'rake' require 'test/filecreation' require 'test/capture_stdout' ###################################################################### class TestTask < Test::Unit::TestCase include CaptureStdout include Rake def setup Task.clear end ...
require 'spec_helper' module UniqueSequence describe Generator do let(:generator) { Generator.new } describe "#get_next" do it "should return an array" do generator.get_next.class.should == Array end it "should return [1] as the first sequence" do sequence = generator.get_...
class ChangeGoalToBeFloatInUsers < ActiveRecord::Migration[5.2] def change change_column :users, :goal, :float, :null => false, :default => 0 end end
#!/usr/bin/env ruby Server = Struct.new(:index, :size, :value, :row, :col, :group) Row = Struct.new(:index, :size, :free, :cols) Group = Struct.new(:index, :capacity, :servers) class DataCenter attr_reader :lines, :rows, :cols, :occupied, :group_count attr_reader :grid attr_reader :servers attr_reader :group...
# Based on code from https://github.com/cmaclell/Basic-Tweet-Sentiment-Analyzer ############################################################################# # Copyright: Christopher MacLellan 2010 # Description: This code adds functions to the string class for calculating # the sentivalue of strings. It...
class AddTotalPriceToTransactions < ActiveRecord::Migration[6.0] def change add_column :transactions, :total_price, :float end end
require 'test_helper' class ApplicationHelperTest < ActionView::TestCase test "full title helper" do assert_equal full_title, "LinksIn" assert_equal full_title("Help"), "Help | LinksIn" end end
class AddWebPageViewableToCustomers < ActiveRecord::Migration def change add_column :customers, :web_page_viewable, :boolean, default: false; end end
class CreateDeprecatedNotebooks < ActiveRecord::Migration[4.2] def change create_table :deprecated_notebooks do |t| t.integer :notebook_id t.integer :deprecater_user_id t.boolean :disable_usage t.string :reasoning t.text :alternate_notebook_ids, array: true t.timestamps null: ...
class CitiesController < ApplicationController skip_before_action :authenticate_user!, only: [:show, :index, :search] def index if params[:query].present? @city = City.where("name ILIKE ?", "%#{params[:query]}%").first if @city return redirect_to city_path(@city) else flash[:...
# ハッシュとはキーと値の組み合わせでデータを管理するオブジェクトのこと # 配列とは複数のデータをまとめて格納できるオブジェクトのこと # ハッシュは {}で囲われていて、配列は[]で囲われている ## 具体例 a = {'japan' => 'yen', 'us' => 'dollar'} puts a #⇛ {"japan"=>"yen", "us"=>"dollar"} ### japanがキーにあたり、yenが値となる。 ## 要素の追加、変更、取得 ## 追加 ### ハッシュ[キー] = 値 で追加可能 ### ハッシュaにitalyというキーでeuroという値を追加する処理 a['italy'] = 'euro...
# This class stores information about drawing class Drawing def self.give_me_a_circle Circle.new end # The class of line class Line end # The class circle class Circle # Create title circle def what_am_i "This is a circle" end end end a = Drawing.give_me_a_circle puts a.what_am_i ...
class UsersController < ApplicationController before_filter :authenticate_user! def index authorize! :index, @user, :message => 'Not authorized as an administrator.' @users = User.all end def show end def update authorize! :update, @user, :message => 'Not authorized as an administrator...
class Image < ActiveRecord::Base require 'open-uri' # OpenURI::Buffer::StringMax = 10240 OpenURI::Buffer::StringMax = 0 belongs_to :gallery after_save :create_dimensioned after_destroy :delete_image validate :check_format def file= (f) self.original_filename = f.original_filename ...
class CreateMessageAttachmentOverlays < ActiveRecord::Migration def change create_table :message_attachment_overlays do |t| t.string :one_to_one_id t.column :message_id, 'CHAR(10)', null: false t.string :overlay, :uuid, null: false t.integer :file_size, null: false t.timestamps ...
class Picture < ApplicationRecord belongs_to :item has_attached_file :image, styles: { high: "1260x900#", medium: "560x400#", thumb: "200x200#" }, default_url: ":style/missing_item_image.jpg" validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ end
require 'test_helper' class Finance::Provider::InvoicesControllerTest < ActionDispatch::IntegrationTest setup do @cinstance = FactoryBot.create(:cinstance) @buyer = @cinstance.buyer_account @provider_account = @cinstance.provider_account @provider_account.create_billing_strategy @provider_account...
require 'spec_helper' describe Sinatra::Hal do def app Sinatra.new do helpers Sinatra::Hal get "/" do hal_links do link :self, "/" link :people, "/people" end end get("/people/1") do hal Person.new end get("/people") do h...
class SessionsController < ApplicationController def new redirect_to '/desk' and return if is_logged? @session = Session.new end def create redirect_to users_path and return if is_logged? @session = Session.new(session_params) if antiflood if @session.valid? user = User.find_by_i...
# Methods for DB-Handling # Communication with DB get '/collections/?' do content_type :json settings.mongo_db.database.collection_names.to_json end # Finding Records # list all Doc in the test collection get '/documents/?' do content_type :json settings.mongo_db.find.to_a.to_json end #find a document by its ID g...
module KeyConcern extend ActiveSupport::Concern included do after_initialize :add_key def add_key self.key ||= SecureRandom.hex end end end
class DatePicker < SimpleForm::Inputs::DatePicker def input(wrapper_options) template.content_tag(:div, super) end end
class Oystercard attr_reader :balance, :entry_station, :journey_history DEFAULT_BALANCE = 0 MINIMUM_AMOUNT = 1 MAX_CAPACITY = 90 def initialize(balance = DEFAULT_BALANCE) @balance = balance @in_use = false @journey_history = [] end def top_up(amount) ...
# frozen_string_literal: true class AuthenticationService < BaseService private attr_reader :headers def initialize(headers) @headers = headers @user = nil end def payload return unless token_present? @data = user if user end def user @user ||= User.find_by(id: user_id) @user ...