Search Results

Search found 1976 results on 80 pages for 'helper'.

Page 7/80 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Multi level menu, active links css highlight. (Ruby on Rails)

    - by klamath
    Site structure: / /products /products/design /products/photo /about I want to see parent menu item also highlighted by CSS, when child is active. (When 'design' or 'photo' is active 'products' should be highlighted too.) I'm using this for child and simple urls: <li class="<%= current_page?(:action => 'design') %>"> <%= link_to_unless_current 'Design', :design %> </li> For 'products' checking should be like: <%= current_page?(:action => 'products') || current_page?(:action => 'design') %> || current_page?(:action => 'photo') %> But triple || is not right, and it's become complicated. I saw a helper, like this one: def current(childs) if current_page?(:action => childs) @container = "active" else @container = "inactive" end end Which is used by: <%= current(:photo) %> So, how to put all my 3 checks for 'products', 'design', 'photo' in one helper? And make possible to use something like <%= current(:products, :design, :photo) %>

    Read the article

  • Which is a better practice - helper methods as instance or static?

    - by Ilian Pinzon
    This question is subjective but I was just curious how most programmers approach this. The sample below is in pseudo-C# but this should apply to Java, C++, and other OOP languages as well. Anyway, when writing helper methods in my classes, I tend to declare them as static and just pass the fields if the helper method needs them. For example, given the code below, I prefer to use Method Call #2. class Foo { Bar _bar; public void DoSomethingWithBar() { // Method Call #1. DoSomethingWithBarImpl(); // Method Call #2. DoSomethingWithBarImpl(_bar); } private void DoSomethingWithBarImpl() { _bar.DoSomething(); } private static void DoSomethingWithBarImpl(Bar bar) { bar.DoSomething(); } } My reason for doing this is that it makes it clear (to my eyes at least) that the helper method has a possible side-effect on other objects - even without reading its implementation. I find that I can quickly grok methods that use this practice and thus help me in debugging things. Which do you prefer to do in your own code and what are your reasons for doing so?

    Read the article

  • Mocking HtmlHelper throws NullReferenceException

    - by Matt Austin
    I know that there are a few questions on StackOverflow on this topic but I haven't been able to get any of the suggestions to work for me. I've been banging my head against this for two days now so its time to ask for help... The following code snippit is a simplified unit test to demonstrate what I'm trying to do, which is basically call RadioButtonFor in the Microsoft.Web.Mvc assembly in a unit test. var model = new SendMessageModel { SendMessageType = SendMessageType.Member }; var vd = new ViewDataDictionary(model); vd.TemplateInfo = new TemplateInfo { HtmlFieldPrefix = string.Empty }; var controllerContext = new ControllerContext(new Mock<HttpContextBase>().Object, new RouteData(), new Mock<ControllerBase>().Object); var viewContext = new Mock<ViewContext>(new object[] { controllerContext, new Mock<IView>().Object, vd, new TempDataDictionary(), new Mock<TextWriter>().Object }); viewContext.Setup(v => v.View).Returns(new Mock<IView>().Object); viewContext.Setup(v => v.ViewData).Returns(vd).Callback(() => {throw new Exception("ViewData extracted");}); viewContext.Setup(v => v.TempData).Returns(new TempDataDictionary()); viewContext.Setup(v => v.Writer).Returns(new Mock<TextWriter>().Object); viewContext.Setup(v => v.RouteData).Returns(new RouteData()); viewContext.Setup(v => v.HttpContext).Returns(new Mock<HttpContextBase>().Object); viewContext.Setup(v => v.Controller).Returns(new Mock<ControllerBase>().Object); viewContext.Setup(v => v.FormContext).Returns(new FormContext()); var mockContainer = new Mock<IViewDataContainer>(); mockContainer.Setup(x => x.ViewData).Returns(vd); var helper = new HtmlHelper<ISendMessageModel>(viewContext.Object, mockContainer.Object, new RouteCollection()); helper.RadioButtonFor(m => m.SendMessageType, "Member", cssClass: "selector"); If I remove the cssClass parameter then the code works ok but fails consistently when adding additional parameters. I've tried every combination of mocking, instantiating concrete types and using fakes that I can think off but I always get a NullReferenceException when I call RadioButtonFor. Any help hugely appreciated!!

    Read the article

  • Rails: Easiest way to provide file downloads?

    - by Schroedinger
    G'day guys, currently have almost finished writing a rails application that allows a CSV download of the database. This is generated when the index is first viewed. Is there an easy way to insert a link to a helper that returns a CSV document? That is to say is it easy to insert links to helpers? This would make a lot of problems I've been having much easier

    Read the article

  • Extending Zend View Helper Placeholder

    - by Sonny
    I was reading the manual about basic placeholder usage, and it has this example: class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { // ... protected function _initSidebar() { $this->bootstrap('View'); $view = $this->getResource('View'); $view->placeholder('sidebar') // "prefix" -> markup to emit once before all items in collection ->setPrefix("<div class=\"sidebar\">\n <div class=\"block\">\n") // "separator" -> markup to emit between items in a collection ->setSeparator("</div>\n <div class=\"block\">\n") // "postfix" -> markup to emit once after all items in a collection ->setPostfix("</div>\n</div>"); } // ... } I want to acommplish almost exactly that, but I'd like to conditionally add more class values to the repeating divs, at time of rendering if possible, when all the content is in the placeholder. One thing I specifically want to do is add the class of "first" to the first element and "last" to the last element. I assume that I'll have to extend the Zend_View_Helper_Placeholder class to accomplish this.

    Read the article

  • Confused as to which Prototype helper to use

    - by user284194
    After reading http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html I just can't seem to find what I'm looking for. I have a simplistic model that deletes the oldest message after the list of messages reaches 24, the model is this simple: class Message < ActiveRecord::Base after_create :destroy_old_messages protected def destroy_old_messages messages = Message.all(:order => 'updated_at DESC') messages[24..-1].each {|p| p.destroy } if messages.size >= 24 end end There is a message form below the list of messages which is used to add new messages. I'm using Prototype/RJS to add new messages to the top of the list. create.rjs: page.insert_html :top, :messages, :partial => @message page[@message].visual_effect :grow #page[dom_id(@messages)].replace :partial => @message page[:message_form].reset My index.html.erb is very simple: <div id="messages"> <%= render :partial => @messages %> </div> <%= render :partial => "message_form" %> When new messages are added they appear just fine, but when the 24 message limit has been reached it just keeps adding messages and doesn't remove the old ones. Ideally I'd like them to fade out as the new ones are added, but they can just disappear. The commented line in create.rjs actually works, it removes the expired message but I lose the visual effect when adding a new message. Does anyone have a suggestion on how to accomplish adding and removing messages from this simple list with effects for both? Help would be greatly appreciated. Thanks for reading. P.S.: would periodically_call_remote be helpful in this situation?

    Read the article

  • Passing data with Rails' link_to helper

    - by mathee
    I am implementing a question-and-answer application with Ruby on Rails. I have MVCs for Questions and Answers. In the home view (index.haml), I list the Questions like this: - @questions.each do |q| %tr %td =link_to q.title, q Next to each of those, I want to add a link that will create a new Answer and pass the id of the Question in that row (continued from the above Haml code) : %td #{link_to 'answer me!', new_answer_path, pass q.id here somehow?} I don't know how to properly pass it and then access it in AnswersController. I tried #{link_to 'answer me!', new_answer_path, :question_id => q.id}, but that was just a guess, and I don't know how to access that in AnswersController. I read the Rails API docs, and I know you can add query, too, but I still don't know how to access the value in AnswersController.

    Read the article

  • Create a helper or something for haml with ruby on rails

    - by Lisinge
    Hello, i am using haml with my rails application and i have a question how the easiest way to insert this haml code into a html file: <div clas="holder"> <div class=top"></div> <div class="content"> Content into the div goes here </div> <div class="bottom"></div> </div> And i want to use it in my haml document like this: %html %head %body Maybee some content here. %content_box #I want to get the code i wrote inserted here Content that goes in the content_box like news or stuff %body I hope you understand what i want to acomplish here. And if there is a easier way to do it please answer how. Thanks!

    Read the article

  • cakephp secure link using html helper link method..

    - by Aaron
    What's the best way in cakephp to extend the html-link function so that I can tell it to output a secure(https) link? Right now, I've added my own secure_link function to app_helpers that's basically a copy of the link function but adding a https to the beginning. But it seems like there should be a better way of overriding the html-link method so that I can specify a secure option. http://groups.google.com/group/cake-php/browse%5Fthread/thread/e801b31cd3db809a I also started a thread on the google groups and someone suggested doing something like $html->link('my account', array('base' => 'https://', 'controller' => 'users')); but I couldn't get that working. Just to add, this is what is outputted when I have the above code. <a href="/users/index/base:https:/">my account</a> I think there's a bug in the cake/libs/router.php on line 850. There's a keyword 'bare' and I think it should be 'base' Though changing it to base doesn't seem to fix it. From what I gather, it's telling it to exclude those keys that are passed in so that they don't get included as parameters. But I'm puzzled as to why it's a 'bare' keyword and the only reason I can come up with is that it's a type.

    Read the article

  • Simplest way to handle and display errors in a Python Pylons controller without a helper class

    - by ensnare
    I have a class User() that throw exceptions when attributes are incorrectly set. I am currently passing the exceptions from the models through the controller to the templates by essentially catching exceptions two times for each variable. Is this a correct way of doing it? Is there a better (but still simple) way? I prefer not to use any third party error or form handlers due to the extensive database queries we already have in place in our classes. Furthermore, how can I "stop" the chain of processing in the class if one of the values is invalid? Is there like a "break" syntax or something? Thanks. >>> u = User() >>> u.name = 'Jason Mendez' >>> u.password = '1234' Traceback (most recent call last): File "<stdin>", line 1, in <module> File "topic/model/user.py", line 79, in password return self._password ValueError: Your password must be greater than 6 characters In my controller "register," I have: class RegisterController(BaseController): def index(self): if request.POST: c.errors = {} u = User() try: u.name = c.name = request.POST['name'] except ValueError, error: c.errors['name'] = error try: u.email = c.email = request.POST['email'] except ValueError, error: c.errors['email'] = error try: u.password = c.password = request.POST['password'] except ValueError, error: c.errors['password'] = error try: u.commit() except ValueError, error: pass return render('/register.mako')

    Read the article

  • url helper diificulty

    - by user281180
    Can anyone help me for the following: I am having the error message. How can I correct that? Error 4 Use of unassigned local variable 'url' on the url.Action... UrlHelper url; string fullUrl = url.Action( "Details", "test", new {test.ID } ); Thanks

    Read the article

  • Help Modifying Generic REST Helper PHP Example Code to Support XML DOM

    - by Jennifer Baker
    Hi! I found this example PHP source code at HTTP POST from PHP, without cURL I need some help modifying the example PHP source to support XML DOM for manipulating a REST API. I thought that if I update the CASE statement for the XML section below from $r = simplexml_load_string($res); to $r = new DOMDocument(); $r->load($res); that it would work but it doesn't. :( Any help would be appreciated. function rest_helper($url, $params = null, $verb = 'GET', $format = 'xml') { $cparams = array( 'http' => array( 'method' => $verb, 'ignore_errors' => true ) ); if ($params !== null) { $params = http_build_query($params); if ($verb == 'POST') { $cparams['http']['content'] = $params; } else { $url .= '?' . $params; } } $context = stream_context_create($cparams); $fp = fopen($url, 'rb', false, $context); if (!$fp) { $res = false; } else { // If you're trying to troubleshoot problems, try uncommenting the // next two lines; it will show you the HTTP response headers across // all the redirects: // $meta = stream_get_meta_data($fp); // var_dump($meta['wrapper_data']); $res = stream_get_contents($fp); } if ($res === false) { throw new Exception("$verb $url failed: $php_errormsg"); } switch ($format) { case 'json': $r = json_decode($res); if ($r === null) { throw new Exception("failed to decode $res as json"); } return $r; case 'xml': $r = simplexml_load_string($res); if ($r === null) { throw new Exception("failed to decode $res as xml"); } return $r; } return $res; }

    Read the article

  • Rails 3.1 text_field form helper and jQuery datepicker date format

    - by DanyW
    I have a form field in my Rails view like this: <%= f.text_field :date, :class => "datepicker" %> A javascript function converts all input fields of that class to a jQueryUI datepicker. $(".datepicker").datepicker({ dateFormat : "dd MM yy", buttonImageOnly : true, buttonImage : "<%= asset_path('iconDatePicker.gif') %>", showOn : "both", changeMonth : true, changeYear : true, yearRange : "c-20:c+5" }) So far so good. I can edit the record and it persists the date correctly all the way to the DB. My problem is when I want to edit the record again. When the form is pre-populated from the record it displays in 'yyyy-mm-dd' format. The javascript only formats dates which are selected in the datepicker control. Is there any way I can format the date retrieved from the database? At which stage can I do this? Thanks, Dany. Some more details following the discussion below, my form is spread across two files, a view and a partial. Here's the view: <%= form_tag("/shows/update_individual", :method => "put") do %> <% for show in @shows %> <%= fields_for "shows[]", show do |f| %> <%= render "fields", :f => f %> <% end %> <% end %> <%= submit_tag "Submit"%> <% end %> And here's the _fields partial view: <p> <%= f.label :name %> <%= f.text_field :name %> </p> <p> <%= f.date %> <%= f.label :date %> <%= f.text_field :date, :class => "datepicker" %> </p> Controller code: def edit_individual @shows = Show.find(params[:show_ids]) end

    Read the article

  • ruby on rails-Problem with the selection form helper

    - by winter sun
    Hello I have a form in witch users can add their working hours view them and edit them (All in one page). When adding working hours the user must select a project from a dropdown list. In case the action is adding a new hour record the dropdown field should remain empty (not selected) in case the action is edit the dropdown field should be selected with the appropriate value. In order to overcome this challenge I wrote the following code <% if params[:id].blank?%> <select name="hour[project_id]" id="hour_project_id"> <option value="nil">Select Project</option> <% @projects.each do|project|%> <option value="<%=project.id %>"><%=project.name%></option> <% end%> </select> <% else %> <%= select('hour','project_id', @projects.collect{|project|[project.name,project.id]},{:prompt => 'Select Project'})%> <% end %> So in case of save action I did the dropdown list only with html, and in case of edit action I did it with the collect method. It works fine until I tried to code the errors. The problem is that when I use the error method: validates_presence_of :project_id it didn't recognize it in the html form of the dropdown list and don’t display the error message (its working only for the dropdown with the collect method). I will deeply appreciate your instructions and help in this matter

    Read the article

  • where to store helper functions?

    - by ajsie
    i've got a lot of functions i create or copy from the web. i wonder if i should store them in a file that i just include into the script or should i store each function as a static method in a class. eg. i've got a getCurrentFolder() and a isFilePhp() function. should they be stored in a file as they are or each in a class: Folder::getCurrent() File::isPhp(); how do you do? i know this is kinda a "as u want" question but it would be great with some advices/best practices thanks.

    Read the article

  • RenderPartial missing from Html Helper in ASP.NET MVC 2

    - by Guy
    I've just converted an application from MVC 1 to MVC 2 using the VS2010 wizard. Not found is the Html.RenderPartial which I have sprinkled around a number of views. I am guessing that this is something that I've done wrong because I see no mention of this as a breaking change in the white papers and docs. Everything I'm using is RTM/RTW and no beta or RC versions.

    Read the article

  • ASP.NET MVC - Disable Html Helper control using boolean value from Model

    - by The Matt
    I am outputting a textbox to the page using the Html helpers. I want to add the disabled attribute dynamically based on whether or not a boolean value in my model is true or false. My model has a method that returns a boolean value: <% =Model.IsMyTextboxEnabled() %> I currently render the textbox like follows, but I want to now enabled or disable it: <% =Html.TextBox("MyTextbox", Model.MyValuenew { id = "MyTextbox", @class = "MyClass" })%> If the return value of Model.IsMyTextboxEnabled() == true I want the following to be output: <input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" /> If it == false, I want it to output as: <input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" disabled /> What is the cleanest way to do this?

    Read the article

  • Skip HTML escape in custom label_tag helper in Rail 3

    - by tricote
    Hi, I have this nice class ErrorFormBuilder that allows me to add the error description near the corresponding field in the form view : class ErrorFormBuilder < ActionView::Helpers::FormBuilder #Adds error message directly inline to a form label #Accepts all the options normall passed to form.label as well as: # :hide_errors - true if you don't want errors displayed on this label # :additional_text - Will add additional text after the error message or after the label if no errors def label(method, text = nil, options = {}) #Check to see if text for this label has been supplied and humanize the field name if not. text = text || method.to_s.humanize #Get a reference to the model object object = @template.instance_variable_get("@#{@object_name}") #Make sure we have an object and we're not told to hide errors for this label unless object.nil? || options[:hide_errors] #Check if there are any errors for this field in the model errors = object.errors.on(method.to_sym) if errors #Generate the label using the text as well as the error message wrapped in a span with error class text += " <br/><span class=\"error\">#{errors.is_a?(Array) ? errors.first : errors}</span>" end end #Add any additional text that might be needed on the label text += " #{options[:additional_text]}" if options[:additional_text] #Finally hand off to super to deal with the display of the label super(method, text, options) end end But the HTML : text += " <br/><span class=\"error\">#{errors.is_a?(Array) ? errors.first : errors}</span>" is escaped by default in the view... I tried to add the {:escape = false} option : super(method, text, options.merge({:escape => false})) without success Is there any way to bypass this behavior ? Thanks

    Read the article

  • Erubis block helper throwing error with concat

    - by DEfusion
    I have a couple of block helpers, here's a simple example of what I'm doing: def wrap_foo foo, &block data = capture(&block) content = " <div class=\"foo\" id=\"#{foo}\"> #{data} </div>" concat( content ) end I'm just trying out erubis and it's giving me the following error: 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.<< Removing the call to concat removes the error but ends up with my wrapper not being rendered Using: Rails 2.3.5 Erubis 2.6.5 And tried this gem that helps Erubis (though 2.6.4) and Rails 2.3 play better together

    Read the article

  • Rails form helper and RESTful routes

    - by Jimmy
    Hey guys, I have a form partial current setup like this to make new blog posts <% form_for([@current_user, @post]) do |f| %> This works great when editing a post, but when creating a new post I get the following error: undefined method `user_posts_path' for #<ActionView::Base:0x6158104> My routes are setup as follows: map.resources :user do |user| user.resources :post end Is there a better way to setup my partial to handle both new posts and editing current posts?

    Read the article

  • Code indentation helper for gedit (python).

    - by aviraldg
    See the little vertical lines? They're damn helpful when writing Python code. Any chance I could get something similar for gedit? I wouldn't mind having to write my own plugin, as long as it's in Python... So: Is there a plugin for this in gedit? If not, would it be possible to write one in Python.

    Read the article

  • Multiple generic parameters on a html helper extension method

    - by WestDiscGolf
    What I'm trying to do is create an extension method for the HtmlHelper to create a specific output and associated details like TextBoxFor<. What I want to do is specify the property from the model class as per TextBoxFor<, then an associated controller action and other parameters. So far the signature of the method looks like: public static MvcHtmlString Create<TModel, TProperty, TController>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Expression<Action<TController>> action, object htmlAttributes) where TController : Controller where TModel : class The issue occurs when I go to call it. In my view if I call it as per the TextBoxFor without specifying the Model type I am able to specify the lambda expression to set the property which it's for, but when I go to specify the action I am unable to. However, when I specify the controller type Html.Create<HomeController>( ... ) I am unable to specify the model property that the control is to be created for. I want to be able to call it like <%= Html.Create(x => x.Title, controller => controller.action, null) %> I've been hitting my head for a few hours now on this issue over the past day, can anyone point me in the right direction?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >