text
stringlengths
10
2.61M
require 'byebug' class MinHeap def initialize(value = nil) @tree = [] if value.is_a?(Array) value.each do |el| self.insert(el) end elsif value self.insert(value) end end def length @tree.length end def get_min @tree.first end def insert(value) @tre...
require 'farm_classes' # We're building a simple representation of a farm. To start, let's make a farm # class with two instance variables. First, we'll need an instance variable # called cash to keep track of how much cash the farm has. Second, we'll need # an instance variable called items that will keep track of wh...
require 'net/http' require 'uri' require_relative "../application.rb" class VRClient @@baseURL = "http://api.vedicrishiastro.com/v1/planets/tropical" def initialize(uid=nil,key=nil) @userID = uid @apiKey = key end def display() return { 'userid' => @userID, 'key' => @apiKey } end def g...
class CreateCharactersPictures < ActiveRecord::Migration[5.0] def change create_table :characters_pictures do |t| t.belongs_to :character t.belongs_to :picture t.timestamps end end end
# # Cookbook Name:: redmine # Recipe:: default # # Copyright 2014, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # filename = "redmine-2.5.1.tar.gz" dirname = File.basename(filename,".tar.gz") install_dir = "/usr/share" remote_uri = "http://www.redmine.org/releases" file_checksum = "1...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ruby_csv_parser/version' Gem::Specification.new do |spec| spec.name = "ruby_csv_parser" spec.version = RubyCsvParser::VERSION spec.authors = ["Leonel Morais"] spec.em...
class SettingsController < ApplicationController def index render json: current_user&.setting.as_json end def create if current_user.setting.present? current_user.setting.update(setting_params) else current_user.build_setting(setting_params).save end end private def setting_p...
# -*- mode: ruby -*- # vi: set ft=ruby : nodes = { 'proxy' => [1, 110], 'compute' => [1, 202], 'controller' => [1, 200], } Vagrant.configure("2") do |config| config.vm.box = "precise64" config.vm.box_url = "http://files.vagrantup.com/precise64.box" #Default is 2200..something, but port 2200...
# represents Invite action, I use this model to track Invite emails delivery status and storing # error responses from Sendgrid api in DB class Invite < ApplicationRecord belongs_to :member end
class AddFontValueToTcTemplateVersion < ActiveRecord::Migration def self.up add_column :tc_template_versions, :font_value, :string, :default=>'normal' end def self.down remove_column :tc_template_versions, :font_value, :string end end
class ListsController < ApplicationController before_action :set_list, only: [:show, :edit, :update, :destroy] def index @list= List.all.order(id: :desc) end def show end def new @list = List.new end def create @list = List.new(params.require(:list).permit(:student_id, :title, :desc...
class TransferSerializer < ActiveModel::Serializer attributes :id, :direction, :amount attributes :status, :note attributes :created_at, :updated_at end
class AddBorrowerAndAdminIdToAssets < ActiveRecord::Migration def change add_column :assets, :borrower_id, :integer add_column :assets, :admin_id, :integer add_index :assets, :borrower_id add_index :assets, :admin_id end end
class Product @@products = [] attr_accessor :title, :price, :stock def initialize(options={}) @title = options[:title] @price = options[:price] @stock = options[:stock] add_to_products end def self.all @@products end def self.indexer(title_to_index) counter = 0 while counter ...
module EOTS class EOTSController < ApplicationController include Rails.application.routes.url_helpers before_action :get_view_context def show # TODO: make this just get the KIND @kind = EOTS::find_kind(params[:kind]) render :show end def send_email @email, errs = EOTS...
module ApiBlueprint class Runner extend Dry::Initializer option :headers, default: proc { {} } option :cache, default: proc { Cache.new key: "global" } option :registry, default: proc { {} } def run(item, cache_options = {}) if item.is_a?(Blueprint) run_blueprint item, cache_option...
FactoryGirl.define do factory :user do password "12345678" status 1 notifications 0 message "" factory :editor do sequence(:first_name) { |n| "user#{n}_myFirstName" } sequence(:last_name) { |n| "user#{n}_myLastName" } sequence(:email) { |n| "user#{n}@example.com" } role...
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "vraptor-scaffold/version" Gem::Specification.new do |s| s.name = "heroku-vraptor-scaffold" s.version = VraptorScaffold::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Filipe Esperandio", "Rodolfo Liviero"]...
module Web module Pages class Perfil < SitePrism::Page set_url '/criar-perfil' element :select_status, '#mui-component-select-status' elements :select_status_items, 'ul.MuiList-root li' element :input_website, '[name="website"]' element :input_conhecimentos, '[name="skills"]' ...
class Ship DESTROYER_SIZE = 2 CRUISER_SIZE = 3 SUBMARINE_SIZE = 3 BATTLESHIP_SIZE = 4 CARRIER_SIZE = 5 attr_reader :size, :status def initialize(size) @size = size @status = "miss" end def self.destroyer new(DESTROYER_SIZE) end def self.cruiser new(CRUISER_SIZE) end ...
class RenameProjectsToChallenges < ActiveRecord::Migration[5.0] def change rename_table :projects, :challenges rename_column :activities, :project_id, :challenge_id rename_column :collaborations, :project_id, :challenge_id end end
require 'spec_helper' # http://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html describe Api::UsersController do describe "GET #index" do it 'should return an a JSON and be successful' do get :index response.headers['Content-Type'].should include 'application/json' response.sh...
require 'rails_helper' describe Job do describe '.enqueue' do let(:args) { { key: 'value' } } let(:job) { double('job') } it 'adds the job to the delayed job queue' do expect(Job).to receive(:new).with(args).and_return(job) expect(Delayed::Job).to receive(:enqueue).with(job) Job.enque...
class ReviewSerializer < ActiveModel::Serializer attributes :id, :rating, :body, :user_id, :userFullName, :cape_id belongs_to :user belongs_to :cape end
require 'spec_helper' require_relative '../../../app/services/exporters/docx_exporter' describe DocxExporter do context "with a valid epub fixture" do let(:epub_fixture) { File.read(File.absolute_path './spec/fixtures/turtles.epub') } describe '#convert_docx' do it "converts do docx" do file =...
# Date: 6/13/2014 # Approx Hours: 5-6 (more if you include other solutions that sucked) ######## ### METHODS USING file_path. BUILD HASH MAPS, AND CALC "water_units" ######## # Build hash of rows using file_path; values go L->R in the row def build_rows_hash(file_path, rows_hash={}) file = File.readlines(file_path) ...
require 'rails_helper' #Imagine Capybara is a human who has never used a computer before and you have to tell them EXPLICITLY everything you want to do #Also these tests DO NOT talk to the _development database, they talk to the _test database, which is completely cleared after each test RSpec.feature "TextacularSea...
require 'test_helper' class DividendsControllerTest < ActionController::TestCase setup do @dividend = dividends(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:dividends) end test "should get new" do get :new assert_response :success ...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
require 'httparty' module FormDefinitionRequest include HTTParty base_uri 'http://phoenix.typeform.com' def self.get_form_title(uid) JSON.parse(get("/form-definition/#{uid}").body)['title'] end end
class Platform < ActiveRecord::Base validates :name, length: { minimum: 1 }, presence: true end
class AddIndexToMembersMemberEmail < ActiveRecord::Migration def change add_index :members, :member_email, unique: true end end
RSpec.describe MultiBug do describe '.use_adapter' do before { MultiBug.use_adapter(adapter) } context 'when using a symbol or a string' do let(:adapter) { :airbrake } it 'loads the provided adapter' do expect(described_class.adapter).to eq(MultiBug::Adapters::Airbrake) end end...
class Trail < ActiveRecord::Base attr_accessible :name, :description, :featured has_many :trail_locations has_many :locations, :through => :trail_locations scope :featured, where(:featured => true) end
# encoding: utf-8 # # © Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 limitation the rights #...
require 'spec_helper' describe "sign in" do # As Confirmed Store #---------------------------------------------------------------------------- context "as confirmed store", :confirmed => true do include_context "as confirmed store" before(:each) do visit new_store_session_path end context ...
module SimpleJsonapi::Node::Resource # Represents a single resource object. class Full < Base # @param options see {Node::Resource::Base#initialize} for additional parameters def initialize(**options) super(options) @attributes_node = build_child_node( SimpleJsonapi::Node::Attributes, ...
module Ray class Target # @return [Ray::Shader] Shader used when drawing on this target def shader @shader ||= simple_shader # must always remain the same object end # @param [Ray::View] view A new view # @yield a block where the view has been changed def with_view(view) old_view ...
class Watchfile < Formula desc "watch & display file, even changing will be displayed!" homepage "https://github.com/Cj-bc/watchfile" url "https://github.com/Cj-bc/watchfile/archive/v0.2.0.tar.gz" head "https://github.com/Cj-bc/watchfile.git" sha256 "43476ea0791b25d0e836d03dbbc361f1cd058fcde6d7e0afdef8bee5ff8...
class FarMar::Vendor < RepeatMethods DATA = "./support/vendors.csv" attr_reader :vendor_id, :name, :number_of_employees, :market_id def initialize(vendor_info) @vendor_id, @name, @number_of_employees, @market_id = vendor_info @vendor_id = @vendor_id.to_i @number_of_employees = @number_of_employees....
class Api::V1::ChatStatementsController < Api::V1::ApplicationController skip_before_action :verify_authenticity_token def create chat_session = ChatSession.find(params[:chat_session_id]) if chat_session.expired? render json: { errors: t('statements.expired_session') }, status: :forbidden else ...
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper def tag_cloud_calculate(tags) classes = %w(tag_weight1 tag_weight2 tag_weight3 tag_weight4 tag_weight5) max, min = 0, 0 tags.each do |t| max = t.count.to_i if t.count.to_i > max min =...
class Band < ActiveRecord::Base has_many :albums, dependent: :destroy has_many :tracks, through: :albums, source: :tracks end
require 'spec_helper' require 'helpers/property' require 'dm-core/property/legacy/date_string' describe DataMapper::Property::Legacy::DateString do include Helpers::Property before(:all) do property(DataMapper::Property::Legacy::DateString) end let(:date_string) { '2010-11-05' } let(:time) { Time.pars...
class CreateProposals < ActiveRecord::Migration def change create_table :proposals do |t| t.integer :user_id t.string :title t.string :object t.string :finality t.integer :scope_id t.integer :subject_id t.timestamps end end end
# Exception handling is for telling your program what to do in the event an error occurs in your program. # It's good for preventing your program from coming to a abrupt halt because of error.
# neutralizer.rb # Problem Code: def neutralize(sentence) words = sentence.split(' ') words.each do |word| words.delete(word) if negative?(word) end words.join(' ') end def negative?(word) [ 'dull', 'boring', 'annoying', 'chaotic' ].include?(word) end puts neutralize('These dull bori...
roman_mapping = { 1000 => "M", 900 => "CM", 500 => "D", 400 => "CD", 100 => "C", 90 => "XC", 50 => "L", 40 => "XL", 10 => "X", 9 => "IX", 5 => "V", 4 => "IV", 1 => "I" } def int_to_roman(int, roman_mapping, numeral = "") return numeral if int < 1 key = roman_mapping.keys.find { |...
class BaaniSerializer < ActiveModel::Serializer attributes :name, :slug, :version, :translations, :lines end
$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'directors_database' require 'pry' # Find a way to accumulate the :worldwide_grosses and return that Integer # using director_data as input def gross_for_director(director_data) total = 0 # Total for a director's movies movie_index = 0 # Counter for the index of t...
class Photo < ApplicationRecord mount_uploader :image, ImageUploader def self.load_photo_by_id( id ) self.find_by_id( id ) end end
# # Cookbook:: dockerhost # Recipe:: dockerengine # # Greg Konradt Dec. 2016 case node['platform_family'] when 'debian' bash 'apt_update_and_add_docker_repo' do user 'root' not_if 'grep apt.dockerproject.org /etc/apt/sources.list.d/docker.list' code <<-EOH apt-key adv \ --keyserver...
ActiveAdmin.register Event do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters permit_params :title, :date, :start_time, :end_time, :details, :location, :points, member_ids: [] filter :members, as: :sel...
namespace :db do desc "sync categories from es. overwirte_model: overwrite/skip" task :sync_brands, [:overwrite_model] => :environment do |task, args| EsBrandsSync.sync(args.overwrite_model) end end
class GossipsController < ApplicationController before_action :authenticate_user before_action :is_permitted_gossip?, only: [:edit, :update, :destroy] def index # Méthode qui récupère tous les potins et les envoie à la view index (index.html.erb) pour affichage puts "#" * 60 puts "Home controller require...
class FontShizuru < Formula head "https://github.com/google/fonts/raw/main/ofl/shizuru/Shizuru-Regular.ttf", verified: "github.com/google/fonts/" desc "Shizuru" homepage "https://fonts.google.com/specimen/Shizuru" def install (share/"fonts").install "Shizuru-Regular.ttf" end test do end end
class Movie < ApplicationRecord has_many :actors has_many :movie_genres has_many :genres, through: :movie_genres validates :title, presence: true validates :director, length: { minimum: 5} validates :year, numericality: { greater_than: 4 } validates :english, inclusion: [ true, false ] validates :plot,...
module ApplicationHelper # Simple helper to inject the page title into pages used in the site. def full_title(page_title) base_title = 'CRM Platform Services API' if page_title.empty? base_title else "#{base_title} | #{page_title}" end end end
module SessionsHelper def domains_list %w( .myapps.ru .myapps.com .salut-boats.ru .realcraftboats.com .realcraftboats.ru .control.myapps.ru .control.myapps.com ) end def sign_in(user) cookies.permanent.signed[:remember_token] = {value: [user.id, user.salt], expires: 1.year.from_now, domain: domains_l...
require 'rails_helper' RSpec.describe InvoicedItem, type: :model do describe 'attributes' do it { should respond_to(:invoice) } it { should respond_to(:product) } it { should respond_to(:sales_order_item) } it { should respond_to(:product_code) } it { should respond_to(:product_name) } it { s...
require "spec_helper" describe Qe::Locale do let(:i18n) { mock("I18n", :locale => :en) } before do stub_const("I18n", i18n) end context "when including extension" do context "before Qe::Locale" do it "raises exception" do expect { mod = Module.new do include Qe::Lo...
# worker_processes 3 # timeout 30 # preload_app true # before_fork do |server, worker| # Signal.trap 'TERM' do # puts 'Unicorn master intercepting TERM and sending myself QUIT instead' # Process.kill 'QUIT', Process.pid # end # defined?(ActiveRecord::Base) and # ActiveRecord::Base.connection.discon...
require_relative 'calculator' require 'rspec' describe Calculator do let(:cal) { Calculator.new } it "should returns 0 for an empty string" do result = cal.calculate("") expect(result).to eq(0) end it "should returns 1 for a string containing 1" do result = cal.calculate("1") expect(result).to eq(1) e...
class TestAnswer < ActiveRecord::Base belongs_to :test_question has_many :registration_test_answers attr_accessible :answer, :is_answer, :position, :active acts_as_list scope: :test_question before_destroy { |record| self.active = false self.save! false } RailsAdmin.config do ...
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 module TwitterCldr module DataReaders autoload :DataReader, "twitter_cldr/data_readers/data_reader" autoload :NumberDataReader, "twitter_cldr/data_readers/number_data_reader" autoload :CalendarDataRead...
require 'test/unit' require 'json' class TestJSON < Test::Unit::TestCase def get_favorite(key, json_data) h = JSON.parse(json_data) return h["favorites"][key] end def test_parse_from_string json = '{"favorites": {"color":"maroon", "fruit":"apple", "language":"ruby"}}' assert_equal('apple', get_...
module WiKey module Views # view object for hot topics class HotTopics def initialize(hot_topics) @hot_topics = hot_topics end def all_hot_topics @hot_topics.topics end def hot_topic_names @hot_topics.topics.map(&:name) end end end end
class Admin::SheltersController < Admin::BaseController def index @shelters = Shelter.all end def new @shelter = Shelter.new end def edit @shelter = Shelter.find(params[:id]) end def update Shelter.find(params[:id]).update_attributes(shelter_params) redirect_to admin_shelters_path ...
class FontDejavuSansMonoForPowerline < Formula head "https://github.com/powerline/fonts.git", branch: "master", only_path: "DejaVuSansMono" desc "DejaVu Sans Mono for Powerline" homepage "https://github.com/powerline/fonts/tree/master/DejaVuSansMono" def install (share/"fonts").install "DejaVu Sans Mono for...
class CreateEventPictures < ActiveRecord::Migration def self.up create_table :event_pictures do |t| t.string :logo,:limit=>50 t.integer :event_id t.integer :user_id t.datetime :created_at end add_index :event_pictures,:event_id end def self.down drop_table :event_pictures ...
module Omada module API module Actions module Create class User include Dry::Transaction step :validate_params step :validate_uniq_user_name step :save private def validate_params(params) # new_user new_user = Om...
# frozen_string_literal: true class Achievement < ApplicationRecord validates_presence_of :name validates :name, uniqueness: true validates_presence_of :description has_many :user_achievements, dependent: :destroy end
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| config.vm.bo...
class User < ActiveRecord::Base has_many :lists # has_many :items # has_many :lists, through: :items has_secure_password # validates :name, :password_digest, :presence => true validates :name, :password, :presence => true def self.find_or_create_by_omniauth(auth_hash) # oauth_email = auth_hash["inf...
class RemoveTeachingPlanLinked < ActiveRecord::Migration def change drop_table :teaching_plan_students drop_table :teaching_plan_courses end end
class UserMailer < ActionMailer::Base default :from => "no-reply@salt-app-dev.stanford.edu" def notification_email(user_email) mail(:to => "bess@stanford.edu", :subject => "User Request to Saltworks: #{user_email}") end end
module Talis # Allows an individual primitive service to set its own Persona environment module OAuthService attr_accessor :oauth_host, :client_id, :client_secret protected # Overrides Talis::Resource.token def token options = { client_id: client_id || Talis::Authentication.client_id...
require "spec_helper" describe Swow::ParamsEncoder do describe "encode" do context "params does not contain arrays" do let(:params) { {param1: "a", param2: "b"} } it "parse params" do expect(Swow::ParamsEncoder.encode(params)).to eq "param1=a&param2=b" end end context "params co...
require 'rails_helper' describe Ability do subject(:ability) { Ability.new(user) } describe 'quest user' do let(:user) { nil } it { should be_able_to :read, Question } it { should be_able_to :read, Answer } it { should be_able_to :read, Comment } it { should be_able_to :read, User } it ...
module Hangman class Word attr_reader :value def initialize _5_to_12_chars = Proc.new { |line| line.length.between?(5, 12) } @value = File.open("text/text.txt") do |f| f.select(&_5_to_12_chars).sample.sub("\n", "").upcase end end end end
module Campaigns module CreateCsvExport class Result attr_reader :csv, :filename, :campaigns_count def initialize(csv:, filename:, campaigns_count:, valid:) @csv, @filename, @campaigns_count, @valid = csv, filename, campaigns_count, valid end def valid? @valid end ...
# frozen_string_literal: true module Robots module DorRepo module Assembly class Base < LyberCore::Robot protected def check_assembly_item return true if assembly_item.item? logger.info("Skipping #{@step_name} for #{druid} since it is not an item") false ...
module ActiveRecord::Turntable module ActiveRecordExt module Transactions # @note Override to start transaction on current shard def with_transaction_returning_status return super unless self.class.turntable_enabled? status = nil if self.new_record? && self.turntable_shard_key...
require_dependency "discovery/application_controller" module Discovery class CareerRecommendationsController < ApplicationController before_filter :authorize def create @category = Discovery::Category.find(params[:category_id]) @career_recommendation = @category.career_recommendations.new(params[:car...
require "spec_helper" describe ClassDetailsController do describe "routing" do it "routes to #index" do get("/class_details").should route_to("class_details#index") end it "routes to #new" do get("/class_details/new").should route_to("class_details#new") end it "routes to #show" do...
class Service < ApplicationRecord enum kind: [:転職サイト, :転職エージェント] validates :name, presence: true, length: { maximum: 50 } validates :url, format: /\A#{URI::regexp(%w(http https))}\z/ validates :kind, presence: true, inclusion: { in: Service.kinds.keys } validates :memo, length: { maximum: 400 } validates...
#!/usr/bin/env rake begin require 'bundler/setup' rescue LoadError puts 'You must `gem install bundler` and `bundle install` to run rake tasks' end if ENV['COVERAGE'] require 'simplecov' SimpleCov.start do add_filter '/test/' add_filter '/features/' end end require 'yard' YARD::Config.load_plugin('y...
class EntriesController < ApplicationController # before_filter :authenticate_request! before_action :require_login before_action :set_flag_by_id before_action :set_entry, only: [:destroy, :upvote, :downvote, :unvote] before_action :require_flag_owner, only: [:destroy] before_action :require_checkin, only:...
require "spec_helper" RSpec.describe "Day 6: Tuning Trouble" do let(:runner) { Runner.new("2022/06") } describe "Part One" do let(:solution) { runner.execute!(input, part: 1) } it "finds the first start-of-packet marker" do expect(runner.execute!("mjqjpqmgbljsphdztnvjfqwrcgsmlb", part: 1)).to eq(7)...
# @since 0.7.0 module TagLib::RIFF::AIFF # The file class for `.aiff` files. # # @example Reading the title # title = TagLib::RIFF::AIFF::File.open("sample.aiff") do |file| # file.tag.title # end # # @example Reading AIFF-specific audio properties # TagLib::RIFF::AIFF::File.open("sample.aiff...
require 'spec_helper' describe "Category Pages" do subject { page } describe "Category View" do let(:category) { FactoryGirl.create(:category) } before { visit category_path(category) } it { should have_page_title(category.name) } context "with children" do before do 5.times { Fact...
class ChangedRolesIndexedResourceTypeResourceIdResourceId < ActiveRecord::Migration def self.up add_index :roles, [:resource_type, :resource_id] add_index :roles, :resource_id end def self.down end end
module QBIntegration module Email def self.build(email_address) email = Quickbooks::Model::EmailAddress.new email.address = email_address email end end end
class CreateAlbumPages < ActiveRecord::Migration def self.up create_table :album_pages do |t| t.integer :user_id t.string :logo t.timestamps end end def self.down drop_table :album_pages end end
class LunchesController < ApplicationController before_filter :authenticate_user! def new @lunch = Lunch.new end def index @lunches = current_user.groups.find(params[:group_id]).lunches end def show @group = current_user.groups.find(params[:group_id]) @lunch = @group.lunches.find(params[:...
class ContactsController < ApplicationController # this controller deals with candidate emails (sent_emails) # and calls # before_filter :login_required layout "qameha" before_filter :load_candidate def index respond_to do |format| format.js end end def new @current_funnel_id = pa...
class AddStderrToCodebooks < ActiveRecord::Migration def change add_column :codebooks, :stderr, :text end end
class CreatePrices < ActiveRecord::Migration[6.0] def change create_table :prices do |t| t.integer :company_id t.string :date t.decimal :open_price t.decimal :high_price t.decimal :low_price t.decimal :close_price t.decimal :volume t.timestamps end end end
class NotificationsController < ApplicationController def link_through @notification = Notification.find(params[:id]) @notification.update read: true if @notification.theme.present? redirect_to item_path(@notification.theme) elsif @notification.code.present? redirect_to item_code_pa...
class GalleriesController < ApplicationController def index @images = Gallery.all end def new @image = Gallery.new end def create return redirect_to new_gallery_path, alert: "Please select any image" if params[:gallery].blank? @image = Gallery.new(img_params) if @image.save redirect...