Giter Club home page Giter Club logo

gon's Introduction

Gon gem — get your Rails variables in your js

Join the chat at https://gitter.im/gazay/gon

Gon. You should try this. If you look closer - you will see an elephant.

Build Status CodeClimate

If you need to send some data to your js files and you don't want to do this with long way through views and parsing - use this force!

Now you can easily renew data in your variables through ajax with gon.watch!

With Jbuilder, Rabl, and Rabl-Rails support!

For Sinatra available gon-sinatra.

For .Net MVC available port NGon.

For elixir Phoenix available PhoenixGon.

Sponsored by Evil Martians

An example of typical use

Very good and detailed example and reasons to use is considered in railscast by Ryan Bates

When you need to send some start data from your controller to your js you might be doing something like this:

  1. Write this data in controller(presenter/model) to some variable
  2. In view for this action you put this variable to some objects by data attributes, or write js right in view
  3. Then there can be two ways in js: + if you previously wrote data in data attributes - you should parse this attributes and write data to some js variable. + if you wrote js right in view (many frontenders would shame you for that) - you just use data from this js - OK.
  4. You can use your data in your js

And every time when you need to send some data from action to js you do this.

With gon you configure it firstly - just put in layout one tag, and add gem line to your Gemfile and do the following:

  1. Write variables by
 gon.variable_name = variable_value

 # or new syntax
 gon.push({
   :user_id => 1,
   :user_role => "admin"
 })

 gon.push(any_object) # any_object with respond_to? :each_pair
  1. In your js you get this by
 gon.variable_name
  1. profit?

With the gon.watch feature you can easily renew data in gon variables! Simply call gon.watch from your js file. It's super useful in modern web applications!

Usage

More details about configuration and usage you can find in gon wiki

app/views/layouts/application.html.erb

<head>
  <title>some title</title>
  <%= Gon::Base.render_data %>
  <!-- include your action js code -->
  ...

For rails 3:

  <%= include_gon %>
  ...

You can pass some options to render_data method.

You put something like this in the action of your controller:

@your_int = 123
@your_array = [1,2]
@your_hash = {'a' => 1, 'b' => 2}
gon.your_int = @your_int
gon.your_other_int = 345 + gon.your_int
gon.your_array = @your_array
gon.your_array << gon.your_int
gon.your_hash = @your_hash

gon.all_variables # > {:your_int => 123, :your_other_int => 468, :your_array => [1, 2, 123], :your_hash => {'a' => 1, 'b' => 2}}
gon.your_array # > [1, 2, 123]

# gon.clear # gon.all_variables now is {}

Access the variables from your JavaScript file:

alert(gon.your_int)
alert(gon.your_other_int)
alert(gon.your_array)
alert(gon.your_hash)

AMD compatible version: include_gon_amd

If your site uses AMD modules you can use the include_gon_amd helper to include the variables and watch function as a module. Options are mostly the same as for include_gon, except for namespace_check, which does nothing and namespace, which is used as the name of the defined module. The end result will look somewhat like the following:

define('yourNameSpace', [], function() {
  var gon = {};
  gon.yourVariable = yourValue;
  // etc...

  return gon;
});

A (very) simplified usage example:

app/views/layouts/application.html.erb

include_gon_amd namespace: 'data'

Some JavaScript module

define(['data'], function(data) {
  alert(data.myVariable);
});

gon.watch - renew your data easily!

You can use gon for renewing your data without reloading pages and writing long js functions! It's really great for some live values.

Supports gon.watch.rabl and gon.watch.jbuilder usage.

Instruction for usage gon.watch.

Usage with Rabl

You can write your variables assign logic to templates with Rabl. The way of writing Rabl templates is very clearly described in their repo.

Profit of using Rabl with gon:

  1. You can clean your controllers now!
  2. Work with database objects and collections clearly and easyly
  3. All power of Rabl
  4. You can still be lazy and don't use common way to transfer data in js
  5. And so on

Instruction for usage gon with Rabl.

Usage with Rabl-Rails

gon.rabl works with rabl-rails. Learn to write RABL the rabl-rails way here.

Add gon and rabl-rails to your environment:

gem 'gon'
gem 'rabl-rails'

Define a rabl template using rabl-rails syntax:

#app/views/users/show.rabl
object :@user
attributes :id, :name, :email, :location

Call gon.rabl in your controller

#app/controllers/users_controller.rb
def show
  @user = User.find(params[:id])
  gon.rabl
end

Usage with Jbuilder

Use gon with Jbuilder as with Rabl:

Instruction for usage gon with Jbuilder.

gon.global

You can use gon for sending your data to js from anywhere! It's really great for some init data.

Instruction for usage gon.global.

Speed up Gon

You can use any JSON Engine you want. Gon uses MultiJson with autodetect mode, so all you need is just require your JSON library.

Contributors

  • @gazay
  • @takiy33

Special thanks to @brainopia, @kossnocorp and @ai.

License

The MIT License

Security Contact

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

gon's People

Contributors

amatsuda avatar asabirov avatar bbasata avatar bushjumper avatar dlupu avatar dnagir avatar edtsech avatar edwardbetts avatar etagwerker avatar gazay avatar gregmolnar avatar irobayna avatar john-bai avatar larskluge avatar maletor avatar moktin avatar nicolasleger avatar novoi-pega avatar petergoldstein avatar phoet avatar rafaelliu avatar razum2um avatar silex avatar strikyflo avatar syoder avatar tommyh avatar toothrot avatar torbjon avatar vijoc avatar willcosgrove avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gon's Issues

defining gon variables in the views

I have a number of views where I need to pass ruby/rails arrays to javascript/jquery code in my haml files. Your gem works fine when I define the gon variables in the controller code, but when I try to assign some variables right within the haml views like so:

  • gon.test_var = "hello there"

and then try to alert it in my jquery/javascript code as shown below:

:javascript

$(document).ready(function() {
$("#tabs").tabs();
alert(gon.test_var);
});

then it throws an error right at the line where I am defining the gon variable, i.e.

  • gon.test_var = "hello there"

So it seems like I cannot assign gon variables a value inside of a view? I know purists frown upon it, but I am not one.

Thanks.

Bharat

Can't bundle gem

Invalid gemspec in [/Users/koss/.rvm/gems/ree-1.8.7-2011.03/specifications/gon-1.1.0.gemspec]: invalid date format in specification: "2011-06-25 00:00:00.000000000 %:z"

Ruby: ruby 1.8.7 (2011-02-18 patchlevel 334) [i686-darwin11.1.0], MBARI 0x6770, Ruby Enterprise Edition 2011.03
Rails: v3.1.0
RubyGems: v1.8.6
Bundler: v1.0.18

Gon as central point to personalized webpages

I have a lot of pages where I'm using full page caching and a bit of javascript magic to update personalized content. Gon is fantastic to instruct the client side js if there's a current user or admin present. However, my current code requires a bit of a work around and I'm interested in extending gon in a few ways or am open to other implementations.

On a fully cached page, gon is watching several variables for me. Here is some of my current code in coffeescript

loadPersonalizedLoginItems = ->
    if gon.hasOwnProperty('current_user')
      gon.watch('current_user', 
        url: '/users/me' 
        interval: 1000
        , gonCurrentUserCallback)
      gon.watch('admin', 
        url: '/users/me' 
        interval: 1000
        , gonAdminCallback)   

gonCurrentUserCallback = (success, data, object) ->
  updateCurrentUserGon('current_user', success, loadLoginItems)

updateCurrentUserGon = (object, data, callback) ->
  gon.current_user = data.replace(/\"/g, "")
  gon.unwatch('current_user', (gonCurrentUserCallback))
  callback()
  false

gonAdminCallback = (success, data, object) ->
  updateAdminGon('admin', success,loadLoginItems)

updateAdminGon = (object, data, callback) ->
  gon.admin = data.replace(/\"/g, "")
  gon.unwatch('admin', (gonAdminCallback))
  callback()
  false

loadLoginItems = ->
  if gon.hasOwnProperty('current_user')
     # Code for specific to a user logged in
  if gon.hasOwnProperty('admin') and gon.admin == "true"
     # code specific for an admin logged in

Here's what's happening above. On application load on a client page, gon knows if there's a current user or not but it doesn't know who. It watches to find out who it is and set that user to current_user and whether it's an admin or not. This is where the code gets ugly.

I couldn't figure out how to pass parameters into the callbacks of the gon.watch functions. Hence the horrendous duplication of code. Further, I had to update the gon object for loadLoginItems() to execute properly. What I'm looking to extend in gon is the ability to pass in the name of the attribute to the callback so that one callback method could be used to update gon's attributes and the continue on towards specific functionality. Or, maybe there's a way for gon watch to update it's attribute and not just return the response? I'd love feedback or questions.

NameError (undefined local variable or method `gon')

So I'm receiving this message with gone: NameError (undefined local variable or method `gon'). When running this on my local machine everything works great. However, when I try to access the app on my production server I receive the above error. Is there any kind of special configuration for gon that needs to be done for the production server? I checked that gon was in my Gemfile.lock file (it is) and I ran gem install gon anyways just to be safe, but I'm still getting the error.
Any ideas?

Gon + RABL + Backbone?

If I'm using RABL + Backbone, do I need Gon to pass variables to Backbone? Are there any examples of such implementation?

set_variable and get_variable

I suggest to move both methods from private to allow users get and set dynamically named variables.
Like for example:

gon.set_variable(Rails.env, true)

Question: how to utilize multiple rabl templates?

In my index action I have a block that looks like this:

respond_to do |format|
    format.html { gon.rabl "app/views/customers/new.json.rabl", as: "customers" }
    format.json { @customers = @account.customers.include_account }
end

How would I reference another separate gon.rabl template in the format.html line so it would produce another gon variable that is only outputted when html is requested?

The other template I want to use would be: gon.rabl "app/views/analytics/customers.json.rabl", as: "analytics"

Thanks!

gon.watch produces 500 internal server error

I got gon setup fine and am able to successfully access data from my model in my JS. However, once I try to use gon.watch this is the error I get:

GET http://localhost:3000/weights?_method=GET&gon_return_variable=true&gon_watched_variable=weight 500 (Internal Server Error) jquery.js:8215

This is my weights.js.coffee

console.log gon.weight if gon
gon.watch('weight', interval: 1000) if gon

My weights controller index action looks like this:

gon.watch.weight = current_user.weight

I even tried adding a callback and am still getting this error.

Thoughts?

P.S. My environment is:

$ rails -v
Rails 3.2.8
$ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.4.0]

Edit 1: the console.log produces the right object:
Object

need a way to pass custom variables onto RABL

in my controller i'd like to pipe two collections of users through the same RABL template (users/index).

at the moment i have to overwrite my instance variable @users to get this working:

@users = current_account.users
gon.rabl 'app/views/users/index', as: 'users'
@users = @deal.users
gon.rabl 'app/views/users/index', as: 'team'

i'm aware that my RABL template is using @users, would be nice if there was a way for gon.rabl to take an :object or :locals parameter, such as:

gon.rabl 'app/views/users/index', as: 'team', locals: {users: @deal.users }

JBuilder no longer requires BlankSlate

the latest version of JBuilder does not require BlankSlate anymore. If the gem is not present in the bundle otherwise, gon raises an error:

/Users/uschi/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.2.0.rc/lib/bundler/rubygems_integration.rb:147:in `block in replace_gem': blankslate is not part of the bundle. Add it to Gemfile. (Gem::LoadError)
    from /Users/uschi/.rvm/gems/ruby-1.9.3-p194@wlw/gems/gon-4.0.0/lib/gon.rb:2:in `<top (required)>'

what would be the best way to deal with this? just removing the require statement would probably break backwards compatibility.

Gon's Jbuilder partial! pathing differs from standard

It looks like Gon's Jbuilder module attempts to do its own partial evalutation before passing the result to Jbuilder. This means that only root-level paths are allowed for partials used via a gon.jbuilder call, which is non-standard.

For example, gon.jbuilder requires something like:

  • partial! "app/views/widgets/_widget.json.jbuilder"

Jbuilder itself accepts one of the following:

  • partial! "widgets/widget"
  • partial! "widget"

Because these two methods differ, they are incompatible. Gon jbuilder partials cannot be used independently of Gon.

The best solution would be to remove any custom Gon partial evalutation and find a way to call JbuilderTemplate.encode with enough context for Jbuilder to resolve its own partials.

A workaround that we are using looks like this:

class PagesController < ApplicationController
    def home
        @widgets = Widget.all
        gon.widgets = JSON.parse(render_to_string(template: "widgets/index.json.jbuilder"))
        render content_type: 'text/html', formats: [:html], layout: 'application'
    end
end

As you can see, it's pretty horrible and I'm sure there is a smoother workaround, but ideally we could just use the gon.jbuilder method directly.

I hope this is enough detail to explain the problem; let me know if anything is unclear!

rails 3.2 "blankslate is not part of the bundle. Add it to Gemfile"

/home/duke/.rvm/gems/ruby-1.9.3-p0@global/gems/bundler-1.0.21/lib/bundler/rubygems_integration.rb:143:in `block in replace_gem': blankslate is not part of the bundle. Add it to Gemfile. (Gem::LoadError)
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@streaming/gems/gon-2.0.5/lib/gon.rb:1:in `<top (required)>'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@global/gems/bundler-1.0.21/lib/bundler/runtime.rb:68:in `require'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@global/gems/bundler-1.0.21/lib/bundler/runtime.rb:68:in `block (2 levels) in require'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@global/gems/bundler-1.0.21/lib/bundler/runtime.rb:66:in `each'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@global/gems/bundler-1.0.21/lib/bundler/runtime.rb:66:in `block in require'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@global/gems/bundler-1.0.21/lib/bundler/runtime.rb:55:in `each'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@global/gems/bundler-1.0.21/lib/bundler/runtime.rb:55:in `require'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@global/gems/bundler-1.0.21/lib/bundler.rb:122:in `require'
    from /home/duke/src/streaming/config/application.rb:7:in `<top (required)>'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@streaming/gems/railties-3.2.0/lib/rails/commands.rb:53:in `require'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@streaming/gems/railties-3.2.0/lib/rails/commands.rb:53:in `block in <top (required)>'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@streaming/gems/railties-3.2.0/lib/rails/commands.rb:50:in `tap'
    from /home/duke/.rvm/gems/ruby-1.9.3-p0@streaming/gems/railties-3.2.0/lib/rails/commands.rb:50:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

undefined local variable or method `include_gon'

Exception raised:
undefined local variable or method `include_gon' for #ActionView::Base:0xbac8298

rails 2.3.11, ruby 1.8.7 (2011-02-18 patchlevel 334) [i686-linux], MBARI 0x8770, Ruby Enterprise Edition 2011.03

Works fine after manual adding helper code to application_helper.rb:

def include_gon
  data = Rails.cache.read('gon_variables') || {}

  script = "<script>window.Gon = {};"
  data.each do |key, val|
    script += "Gon." + key.to_s + val.to_json + ";"
  end
  script += "</script>"
  script.html_safe
end

Render JSON with root false

Hi,

Thank you for your awesome gem, I'm using this to glue my backbone.js code with rails.

One thing I want to know is, in default rails, I can do things like this

user = User.find(xx)
user.to_json(:root => false)

to get rid of some nested key name. But now, after adapted gon, it automatically help me finished the covert between rails object and json. Therefore I don't have a place to do the render with root false.

include_gon causes nil object error

In my Rails 3.0.9 app, I recently added gon (which is amazing), but I found that I get this error on a page, "http://localhost:3000/[email protected]&password=admin":

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]=
Extracted source (around line #10):

7: <html>
8: <head>
9:  <title>MyApp</title>
10:     <%= include_gon %>
11:     <%= stylesheet_link_tag :all %>
12:     
13:     <!--Include JS lib files-->
(etc.)

I initially go to that url so as to login immediately, which this app requires (the app's actually meant to run in Qt webkit).

The full trace looks like this:

gon (3.0.3) lib/gon/request.rb:27:in `clear'
gon (3.0.3) lib/gon.rb:42:in `clear'
gon (3.0.3) lib/gon/helpers.rb:14:in `include_gon'
app/views/layouts/application.html.erb:10:in `_app_views_layouts_application_html_erb___882655896_2176643980_0'
actionpack (3.0.9) lib/action_view/template.rb:135:in `send'
actionpack (3.0.9) lib/action_view/template.rb:135:in `render'

Interestingly, on other pages, gon seems to work fine...

Issue with "push" method

I tried by, both, running gon.push({ :random_var_name => "blah" }) or with an object which respond_to? :each_pair but with no effects: no errors returned, just "gon" stays empty (watched through pry). Any point towards what is happening and how can I solve this?

Clear a gon variable from JavaScript

It would be a great addition if we could clear a gon variable from the JavaScript.
Seeing as how JavaScript can interact with cookies from the client, this ought to be possible.

xss

gon.my_var = "</script><script type='text/javascript'>alert('pwned');</script>"

at a minimum you need to escape "</" to "</" and u0000-u0001F to \u00xx and u2028 and u2029 (crazy line terminators). however, you may also consider escaping "<" -> \u003C and ">" -> \u003E instead of just escaping the closing tag. i don't know enough about how browsers detect the end of the script tag to know if "</" is enough.

see section 7.8.4 for string literals and section 7.3 for line terminators:
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

Can't use watch just once

Hi!

I've succeed use gon.watch with an inverval argument but not without it.

Some examples to illustrate.
In all examples I assume <%= include_gon(:init => true, :watch => true) %> is set in head and a gon variable called pins is set with a rabl template gon.watch.rabl "app/views/pins/index.json.rabl", as: "pins" in my controller.

Working A simple coffeescript working with interval set.

jQuery ->
  blublu = (pins) ->
    console.log("blu")

  gon.watch('pins', interval: 1000, blublu)

Expected : "blu" is print in console every second
Result : "blu" is printed in console every second OK

Not Working A simple coffeescript not working without interval

jQuery ->
  blublu = (pins) ->
    console.log("blu")

  $("#call_blublu").click ->
    console.log("clicked")
    gon.watch('pins', blublu)

Expected : "clicked" is printed in console and then "blu" is printed in console
Result : only "clicked" is printed in console NOT OK

Maybe I'm misunderstanding something about gon.watch so I tried to explane as simple as possible what I want with these little examples.
Thanks for your help!

Variable name

Beautiful gem! :)
Maybe create ability to customize variable name?
Thanks.

Gon not accessible in application controller

Thanks for the cool gem!

Not sure if I am misunderstanding something but if I try to assign a gon variable in the Application Controller, it does not take (i.e. does not show up in the js output). This seems pretty important as I would guess others also would have variables which are used application wide... If there is a way to do this already I would love to hear.

Is it possible to include GON through js?

I'm trying to write my own gem with using gon gem.
So is it possible to install them without adding <%= include_gon %> to app/views/layouts/application.html.erb?

Maybe I can just include gon inside my js files or something like it.

Thank you!

Gon variables persisted if no gon variables are set

It appears that the gon variables aren't being cleared out across requests if a gon variable isn't set on the new request.

Steps to recreate:

  1. In application layout include_gon
  2. Have 2 actions, #foo and #bar.
  3. #foo action should have no gon assignments
  4. #bar should have gon.a = "b"
  5. go to #foo page. include_gon => "" (which is good)
  6. go to #bar page. include_gon => "window.gon = {}; gon.a = 'b' "; (which is good)
  7. go to #foo page. include_gon => "window.gon = {}; gon.a = 'b' "; (which is bad)

Is this known/desired functionality? My goal was to have "include_gon" in my global application layout, and it would only have variables if I assigned them in the action (or in a before_filter).

This is on Rails 3.1.3

Tom

PS Thank you for this gem - I was already using the 2 other methods described in ryanb's railscast, and gon seems like a much cleaner approach

Default RABL/Jbuilder template path

It would be nice if the rabl/jbuilder template could automatically use the same template as the controller action. This seems like a good behavior to preload some records into JavaScript which can then later be fetched by the same action.

def index
  @products = Product.all
  gon.rabl as: "products"
  # would load "index.json.rabl"
end

Temporal dependency: gon < jbuilder

Because the JBuilder code is only conditionally required, there's a minor temporal dependency for Gon that feels unnecessary. If JBuilder isn't included before Gon, Gon has no JBuilder support and throws an error at gon.jbuilder; the same would apply for RABL support.

Possible solutions:

  • document the temporal dependency
  • make those requires unconditional: there is probably a minimal performance difference and there is one less thing that can go wrong.

gem 'rabl' must be before gem 'gon'

This works correctly:

gem "rabl"
gem "gon"

But this doesn't work:

gem "gon"
gem "rabl"

When I call gon.rabl I get an exception "You should define Rabl in your Gemfile".

I think this is because:

  • Gon is loaded before RABL
  • So if defined?(Rabl) is false when lib/gon.rb is loaded
  • So gon/rabl is never required
  • So defined?(Gon::Rabl) is false in gon.rabl
  • So calling gon.rabl raises an exception

I'm not sure what's the best way to fix that, but at least a note in the Readme would be helpful.

TypeError in gon.jbuilder for templates that have partials

When a jbuilder template that includes a partial (another jbuilder template) is rendered through gon.jbuilder, a TypeError exception is raised. jbuilder renders my partial-using template correctly for normal JSON requests. Gon renders my template correctly when the partial code is moved inline.

TypeError in MyController#some_action

gon (2.0.4) lib/gon/jbuilder.rb:12:in `eval'
jbuilder (0.3) lib/jbuilder.rb:84:in `each'
jbuilder (0.3) lib/jbuilder.rb:84:in `extract!'
jbuilder (0.3) lib/jbuilder.rb:95:in `call'

View helpers in rabl template throws 'undefined method' if used with gon

My rabl templates are working fine if I use it outside gon for example as a response to XHR requests, but if I use the same template with gon it throws error in view helper methods used in the rabl templates. In Rabl, using Rails view helpers are allowed, so it seems that gon might be causing some issue in there, is it an issue with the view context ?

Here's my sample rable template:

attributes :id, :name, :created_at
node(:time_ago) { |m| distance_of_time_in_words(m.created_at, Time.now) }

There seems to be an issue filed in the Rabl repository related to this problem:
nesquena/rabl#147

Thanks,
Arnab

use gon in helpers?!

Is it possible to use from within a helper?! I tried the simple include Gon::Helpers, but this doesn't work (ActionView::Template::Error (undefined local variable or method `gon')...

Gon::JBuilder and URL helpers

It seems as if url_helpers are not available within jbuilder templates.

This is the error I get if try to use a URL helper in a jbuilder template loaded using gon.jbuilder.
NoMethodError (undefined method `blah_blah_url' for Gon::Jbuilder:Module):

Gon requires Ruby 1.9?

I am stuck with Ruby 1.8 for now and am unable to use the latest version of gon. I'm using gon with rabl and I get this "Possible wrong require order problem" error, which I discovered is happening because the check for Gon.constants.include?(:Rabl) uses a 1.9 method. Because of this, for now we are stuck with v 3.0.5. I'm not sure if the rest of the code requires Ruby 1.9 or if it's just this check here. If it's possible to fix this check so 1.8 continues to be supported that would be wonderful, otherwise a note in the documentation on Ruby version requirements would be helpful. Cheers.

Gon does not work in respond_to js.erb

Anyway, it might be my stupidity, but if you have time, please help me to clarify on the usage.

in index view
<%= form_tag("/visitors/new_visitor", :remote => true) do %>
some field_tag here ...
<%= submit_tag "Switch" %>
<% end %>

in visitors controller
def new_visitor
@gonlat = 456
gon.gonlat = @gonlat
respond_to do |format|
format.js
end
end

in new_visitor.js.erb
alert(gon.gonlat);
=> this does not work when i click submit button in my view

but if i use it in my controller as
def index
@gonlat = 456
gon.gonlat = @gonlat
end

visitor.js.erb
alert(gon.gonlat);
=> this works well

So, is it how it supposed to be or I had made some mistake?

Merge

  1. I have this code in controller:
Gon.fst = 'First'
debugger
  1. In debugger i get:
Rails.cache.read('gon_variables') # => {"fst" => "First"}
  1. When i change code in controller (removed fst key):
Gon.snd = 'Second'
  1. In debugger:
Rails.cache.read('gon_variables') # => {"fst" => "First", "snd" => "Second"}

After updating to gon 3.0.2 rails helper method not working

The rails helper methods: path_to_image and image_path (same thing, 1 is an alias) now return /images/YOURIMAGE.PNG instead of /assets/YOURIMAGE.PNG which is what it's supposed to return.

If I revert to an older version of gon -- say 2.3.0 the helper methods work as intended.

gon.request won't set

Hi,

When I get gon.request = 'foo' it's no available in the view, but when doing gon.foo = 'bar' it works just fine.... could this be a possible bug?

Remove RABL dependency

It's a bit strange that RABL is a dependency considering it is not needed to use the primary functionality of the gem. If one wants to use Jbuilder instead, it still requires they install RABL with Gon. Having the user add rabl to their Gemfile seems like a good solution to me and parallels the way jbuilder works. What do you think?

Methods defined by helper_method are not available in JBuilder templates.

I defined a helper_method in my controller and unfortunately it's not available in the JBuilder views I use through Gon.

I get undefined local variable or methodcurrent_user' for Gon::Jbuilder:Module` exceptions.

The view:

json.call(current_user, :id, :name, :email)

The controller:

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :current_user
  before_filter :seed_data


  private

  def seed_data
    gon.jbuilder 'app/views/users/user.json.jbuilder', as: 'current_user', locals: { current_user: current_user }
  end


  def current_user
    return nil unless cookies.signed[:persistence_token]
    @current_user ||= User.find_by_persistence_token(cookies.signed[:persistence_token])
  end
end

Using locals didn't solve the problem so for now I put current_user into @the_current_user and I use this variable in the view.

Is it possible to make such methods available in the view?

Gon in jruby and using a raphael map

So my gon works great thru jruby, and I can read the object inside my coffeescript. And that was awesome.

But when I try to assign this gon data to the Raphael map, the data is not picked up. The other path of json object thru the views work, so I think the map is working, but not reading the gon data properly.

Thanks for this awesome gem, I am sure this will get better and very useful.

gon.watch with unix top sample doesn't work on ubuntu 12.04?

With Rails 3.2.11, Ruby1.9.3.From development log are:

Started GET "/top?_method=GET&gon_return_variable=true&gon_watched_variable=top" for 127.0.0.1 at 2013-01-20 12:33:51 +0800
Processing by HomeController#top as */*
  Parameters: {"gon_return_variable"=>"true", "gon_watched_variable"=>"top"}
Completed 200 OK in 14ms (Views: 0.3ms | ActiveRecord: 0.0ms)
    top: unknown argument 'l'
usage:  top -hv | -bcisSH -d delay -n iterations [-u user | -U user] -p pid [,pid ...]

when i change top -l1 to top, it seems the page just loading forever without any output.Did i make some mistake?@gazay

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.