ruby instace variable scope in homecontroller - ruby-on-rails

i have class HomeController
class HomeController < ApplicationController
def event_one
Req = **endpoint.connection**
res = req.body**(json format)**
#events = res
end
def event_two
#events
end
end
Can i use one instance variable(#events) which got response from endpoint in event_one method,from another event_two method.

try using this DRY code:
class HomeController < ApplicationController
before_action :set_events, only: [:event_one, :event_two]
def event_one
#your code here
# for example puts #events
end
def event_two
#your code here
# for example puts #events
end
private
def set_events
req = **endpoint.connection**
res = req.body**(json format)**
#events = res
end
end

you can achieve use a private method to set evnets
class HomeController < ApplicationController
def event_one
set_events
end
def event_two
set_events
end
private
def set_events
Req = **endpoint.connection**
res = req.body**(json format)**
#events = res
end
end
You can also call this method using filter of you want to set for every action of this controller.
Hope this will help!

Related

How to break down decent-exposure code to classic Rails way?

Can anyone break this code down for me and explain how this can be done in classic Rails way with callbacks(if any) and methods?
class SearchController < ApplicationController
expose :search_result, -> { SearchService.new(search_params).call }
def search_params
params.permit(:q, :scope)
end
end
class SearchController < ApplicationController
def index
#search_result = SearchService.new(search_params).call
end
def search_params
params.permit(:q, :scope)
end
end
expose :search_result, -> { SearchService.new(search_params).call } creates a variable #search_result

Issue with HomeController showing undefined method

I am trying to pass stored_products from shopify into a Rails app but keep getting a home controller error at https://f588240c.ngrok.io/ i have made updates, with no luck and restarted the server a number of times with no luck.
Any help would be welcomed. Heres the code
class Api::V1::HomeController < ShopifyApp::AuthenticatedController
def index
#products = ShopifyAPI::Product.find(:all, params: { limit: 10 })
#products.each do |product|
StoredProduct.where(shopify_id: product.id)
.first_or_create do |stored_product|
stored_product.shopify_id = product.id
stored_product.shopify_title = product.title
stored_product.shopify_handle = product.handle
stored_product.shopify_image_url = product.image.src
stored_product.shop_id = #shop.id
stored_product.save
product.images.each do |image|
ProductImage.where(shopify_id: image.id)
.first_or_create do |product_image|
product_image.image_url = image.src
product_image.stored_product_id = stored_product_id
product_image.shopify_id = image.id
end
end
end
end
#stored_products = StoredProduct.belongs_to_shop(#shop.id)
end
end
From the authenticated controller
private
def set_shop
#shop = Shop.find_by(id: session[:shopify])
set_locale
end
from the store_products.rb file
class StoredProduct < ApplicationRecord
belongs_to :shop
has_many :product_images
scope :belongs_to_shop, -> shop_id { where(shop_id: shop_id) }
end
For this specific issue/code tutorial, the private set_shop method should be set like follows:
def set_shop
#shop = Shop.find_by(id: session[:shop_id])
set_locale
end
The other answer has params instead of session
The problem is that #shop is nil. The error message says it cannot call the method .id on NilClass.
In the image I can see that you have a shop_id in the params so you might just need to change your code here:
def set_shop
#shop = Shop.find_by(id: params[:shop_id])
set_locale
end
But that depends on your code, so please double check.

dup or clone action in rails

Well im going to clarify im doing it
class DuplicatesController < ApplicationController
before_action :set_venue, only: [:new]
def new
end
def create
if #venue.duplicate(venue_params)
flash[:success] = t('controller.create.success',
resource: Venue.model_name.human)
redirect_to admin_venue_url #venue
else
flash[:warning] = #venue.errors.full_messages.to_sentence
render :new
end
end
private
def set_venue
#venue = Venue.friendly.find params[:venue_id]
end
end
def venue_params
params.require(:venue).permit(:name,
:address,
:address_complement,
:city,
:phone)
end
end
def duplicate
(name,
address,
address_complement,
city,
phone)
new_venue = self.dup
new_venue.update_attributes(description: self.description,
logo: self.logo,
opening_time: self.opening_time,
closing_time: self.closing_time,
ally_id: self.ally_id)
new_venue.save
end
How can I call those params in my duplicates controller, thanks
I need to set the attributes, after create a dup because I want to save a new record with new information, but i dont know to do it in my method, someone could explain me
Thanks.
Probably the best way to do it is to pass only id/slug of original model.
Then your duplicates_controller.rb can look similar to this:
class DuplicatesController < ApplicationController
def create
old_venue = Venue.friendly.find(params[:id])
venue = old_venue.dup
venue.attributes = venue_params
if venue.save
# success render
else
# error render
end
end
private
def venue_params
params.require(:venue).permit(:permitted_attributes) # id should not be there
end
end
Of course you can refactor it, but I do not think it is needed in this situation.
Or my favourite is to change VenueController#create to something like this to allow creating from another instance:
if copy_from_id = params[:copy_from_id]
#copy_source = Venue.find_by(id: copy_from_id)
#venue = #copy_source.dup
#venue.attributes = venue_params
else
#venue = Venue.new
end
if #resource.save
...
else
...
end

confused, where are the defintions of show and index actions?

I'm looking at this code, I can see that is says actions: show and index but where are the methods show and index??
http://github.com/railsdog/spree/blob/master/core/app/controllers/products_controller.rb
class ProductsController < Spree::BaseController
HTTP_REFERER_REGEXP = /^https?:\/\/[^\/]+\/t\/([a-z0-9\-\/]+\/)$/
#prepend_before_filter :reject_unknown_object, :only => [:show]
before_filter :load_data, :only => :show
resource_controller
helper :taxons
actions :show, :index
private
def load_data
load_object
#variants = Variant.active.find_all_by_product_id(#product.id,
:include => [:option_values, :images])
#product_properties = ProductProperty.find_all_by_product_id(#product.id,
:include => [:property])
#selected_variant = #variants.detect { |v| v.available? }
referer = request.env['HTTP_REFERER']
if referer && referer.match(HTTP_REFERER_REGEXP)
#taxon = Taxon.find_by_permalink($1)
end
end
def collection
#searcher = Spree::Config.searcher_class.new(params)
#products = #searcher.retrieve_products
end
def accurate_title
#product ? #product.name : nil
end
end
My guess is that the actions method is loaded with resource_controller as a module from the lib directory. Then calling the actions method creates the index and show methods.
The class inherits from Spree::BaseController and ActionController. Spree::BaseController has method action which takes method names as messages.

Error using private or protected methods in subclasses of ApplicationController

I have a filter shared between some controllers, which is primarily declared as private in ApplicationController. This method sets find and pagination conditions for controllers.
class ApplicationController < ActionController::Base
...
protected # or private
# Define parametros de busca
def set_find_opts(klass)
#filter = params[:f].to_i || nil
#order = klass.set_order params[:o]
#opts = { :page => params[:page] }
#opts[:order] = #order if #order
end
...
end
class Admin::UsersController < AdminController
...
before_filter(:only => :index) {|c| c.set_find_opts User }
...
end
I'm getting this error:
1) Error:
test_should_get_index(Admin::UsersControllerTest):
NoMethodError: protected method `set_find_opts' called for #<Admin::UsersControl
ler:0x848f3ac>
app/controllers/admin/users_controller.rb:4
functional/admin/users_controller_test.rb:9:in `test_should_get_index'
Why it happens?
You can't send private/protected messages with an explicit receiver (object.protected_method) like you are doing in your block. You can try c.send(:set_find_opts, User) or c.instance_eval { set_find_opts(User) }.

Resources