FAQ Database Discussion Community


How to condense this into a single function?

javascript,jquery,function,dry
I am really new to JS/JQuery, I cant figure out how to keep this code D.R.Y, if its even possible at all I don't know. I am using JQuery for an on hover effect with an image. Box1 being the div and the img_hover_effect being the overlay on hover. JS:...

Rails simple DRY JSON response questions

ruby-on-rails,json,dry
I'm building a Rails API and finding myself falling into the same patter: def some_generic_customer_method @customer = Customer.where(id: params[:id]).first if @customer.present? ##execute some code else respond_to do |format| msg = {:status => "FAILED", :messages => "Could not find customer"} format.json { render :json => msg } end end end Is...

How to use one view for multiple routes in Ember

ember.js,view,routes,dry
I have a view in views/posts/index.js. And I have one route for list of posts and another for search engine. How can I use it in the second route, which is a search engine?

DRY vs appropriate separation of concerns

css,ruby-on-rails-4,dry,separation-of-concerns
I have a situation where a different background image is rendered based on the @page_name variable. It seems to me like I could either do something like this in the HTML: <div class="jumbotron" style="background-image: url(<%= asset_path "Jumbotron/#{@page_name}.gif" %>)"> Which would be the DRYest, or I could actually use the CSS...

Preciseness of DRY Principle [closed]

html,css,dry
I've been diving into html/css over the past few weeks and am now trying to optimize my code with the DRY principle (along with SMACSS/OOCSS/BEM). I believe I have a decent understanding of it all, but there's one thing that's still unclear to me. Should the DRY principle be applied...

How could I compress/optimize this code (jQuery)?

javascript,jquery,dry
I'm looking to optimize this code and hopefully take less space. I'm fairly new to JavaScript and jQuery, so I'm not quite sure how it would be done. rankedSolo5["Wins"] = jsonData.playerStatSummaries[5].wins; $("#rankedWinsSolo5 .statsValue").html(rankedSolo5["Wins"]); rankedSolo5["Assists"] = jsonData.playerStatSummaries[5].aggregatedStats.totalAssists; $("#rankedAssistsSolo5 .statsValue").html(rankedSolo5["Assists"]); rankedSolo5["Kills"] = jsonData.playerStatSummaries[5].aggregatedStats.totalChampionKills; $("#rankedKillsSolo5...

HTML attributes and PHP - where to draw the line between conflicting principles

php,dry,class-attributes
I have an HTML file which contains two tabs like this (besides lots of other stuff): <div id="tabs"> <div id="tab1" class="">Tab 1</div> <div id="tab2" class="">Tab 2</div> </div> This HTML file is used in several contexts, so it seems reasonable to have one single HTML file that I include with PHP...

How to avoid repetition of .then() and .catch() after $http requests?

javascript,angularjs,promise,dry
I have a simple userAPI service in my angular app: app.service('userAPI', function ($http) { this.create = function (user) { return $http .post("/api/user", { data: user }) .then(function (promise) { return promise.data }) .catch(function (error) { return error.data }) } this.read = function (user) { return $http .get("/api/user/" + user.id) .then(function...

Reuse conditional statements in sub-classes.

java,abstract,dry,abstract-methods
I have below classes: public abstract class Parent { public abstract boolean checkName(String str); } public class Child1 extends Parent { public static final String NAME = "CHILD1"; @Override public boolean checkName(String str) { //check input validity: if (!NAME.equals(str)) { throw new IllegalArgumentException("some thing"); } //... } } public class...

How to DRY (myself) in Django form for Create and Edit Form

django,django-forms,django-templates,dry
I created two forms in Django for the same model, named AccountCreateForm and AccountEditForm. The Account model has say three fields and each of them has a few form attributes such as max_length, help_text, error_messages. For example, class AccountCreateForm(forms.Modelform): name = forms.CharField(max_length=50, required=True, label='Account Name', help_text='50 characters max', error_messages={'required': 'Please...

The best way to split struct into function argument list

c++,c,dry
I have function like: void funcName(arg1, arg2, arg3[ = someDefault], ... , argN) And I have a struct like struct Args { arg1; ... argN; } Is there any DRY and pretty solution to init structure from function args and to send structure into function if I can`t change function...

How do I DRY up this script?

jquery,css,navigation,dry
I have been plugging away at this navigation code, and I finally got the 1st layers of my menu to work. Yay! But I've noticed that my code ONLY works on the 1st layers. Well, kinda. Open menus are supposed to close when you click on a different menu. It...

Any ideas on simplify my code? [closed]

javascript,jquery,dry
Any ideas how to apply DRY practice here? I know that I am repeating to much and I don't like it. But I don't know how to solve it. It would be great to simplify this unit convertor. Thanks everyone for any help. $(':input').bind('keypress keydown keyup change',function(){ var input =...

Python “private” classmethod and DRY

python,dry,class-method
Occasionally, a class will have a "private" @classmethod which other methods call: class FooClassThisSometimesHasALongNameEspIfAUnittestSubclasss(...): @classmethod def foo(): ... def bar(self): ... FooClassThisSometimesHasALongNameEspIfAUnittestSubclasss.foo() ... As can be seen, the class name is repeated; it's admittedly probably not serious enough to cause a meltdown of current technology followed by a zombie apocalypse,...

How to eliminate repeat code in a for-loop?

java,design,dry
I have implemented two member functions in the same class: private static void getRequiredTag(Context context) throws IOException { //repeated begin for (Record record : context.getContext().readCacheTable("subscribe")) { String traceId = record.get("trace_id").toString(); if (traceSet.contains(traceId) == false) continue; String tagId = record.get("tag_id").toString(); try { Integer.parseInt(tagId); } catch (NumberFormatException e) { context.getCounter("Error", "tag_id not...

Returning save! value after code with DRY

ruby-on-rails,save,dry
Hi I'm trying to write a code that is functionally equivalent to: def model_method(args) ... obj.save! ... void code assuming save! worked ... return obj.save! end Normally I would use an after_save callback, however there are arguments passed into this model's method that I need to use for the ...code......

how to recode my jquery/javascript function to be more generic and not require unique identifiers?

javascript,jquery,html,generics,dry
I've created a function that works great but it causes me to have a lot more messy html code where I have to initialize it. I would like to see if I can make it more generic where when an object is clicked, the javascript/jquery grabs the href and executes...

A DRYer way to upgrade customer from 1 to 3 to 5 times a week (i.e., Date math!)

ruby,date,ruby-on-rails-4,dry
This is one of those things that's super obvious to people, but code wise I'm struggling with how to write it. A customer can be on one of 3 plans: Once a week (1) - on Monday, where product is $15 each (or $15 for the week) Three times a...

Presenting Validation errors in View, avoiding repetition

validation,laravel,dry,blade,laravel-validation
What is the best way to loop through errors from Validator and then present them right after the form element without resorting to lots of @if clauses? This is not rather elegant nor DRY: <input name="name" /> @if (isset($errors['name'])) <div class="error">{!! $errors['name'] !!}</div> @endif <input name="email" /> @if (isset($errors['email'])) <div...

DRY voting methods

ruby-on-rails,ruby,dry,voting-system
I have a prompt asking to write my up_vote and down_vote methods in only two lines using 'redirect_to' and the 'update_vote!' method as presented below. Implementing redirect_to is easy enough, but I'm not quite sure how to write my up/down_vote methods concisely using the existing 'update_vote!' method. Any help is...

Consolidate Similar Functions DRY

javascript,dry
I have these 2 functions that are very similar. I thought about using strings and eval('Man'), but I would love to avoid this, if possible. How can abstract the two, so it's only one function? function showMan() { widget.classList.add(toggle); fx.wipeOut({ node: calWoman }).play(); fx.wipeOut({ node: pointsWoman }).play(); pointsMan.classList.remove(toggle); fx.wipeIn({ node:...

Dynamically disabling/omitting Apache configuration directives (DRY)

apache,apache2,ssl-certificate,dry,vhosts
I am working on a product that runs Apache, and i'm trying to make the configuration more DRY — right now there are many different vhost configs that get loaded in different situations but are 90% identical, and this is very tedious to deal with when a change needs made....

Refactoring WHERE clause in T-SQL for Access

sql,ms-access,dry
I am currently implementing a heavy-duty WHERE clause involving 30 fields from a table, is there a way to refactor: WHERE ( (table.field1 LIKE "*" & Forms!SearchForm!txt_box1 & "*" Or Forms!SearchForm!txt_box1 Is Null) AND (table.field2 LIKE "*" & Forms!SearchForm!txt_box2 & "*" Or Forms!SearchForm!txt_box2 Is Null) AND ... And so on...

Reuse laravel form partial

php,forms,laravel,dry,blade
When reusing a form partial with a Form::model() and Form::open() I'm running into problems on how to use default values. For example when using the following form partial partials/form.blade.php: {!! Form::text('myfield', 'Default') !!} {!! Form::text('otherfield', '123') !!} {!! Form::text('yetanother', 'Yet another default') !!} // Etc I would include it as...

C# Refactoring gigantic switch statement for ordering with LINQ

c#,asp.net-mvc,linq,dry
My problem is repetitive code: a not so DRY switch statement. So I have a table with 12 columns that can be ordered by descending or ascending on click. My current solution is the use of a switch statement that checks which column was clicked. The sortable properties: This is...

How could I avoid all this repetition with enumerated-like properties?

c#,dry
I have just found an insidious error caused by index mismatching inside my class, and this was due to code being repetitive and sequence-like. My question: would there be another, more sensible way to expose properties (being used with WPF for databinding) without all this horrid repetition? Code (with comments...

Multiple looped ajax requests with one callback

javascript,jquery,ajax,dry
Like in this article, I have several ajax requests to perform followed by 1 action. However, the difference is that all my ajax request only differ by one incremental parameter like this: $.when( // ajax requests // 1 $.ajax({ url:"https://www.aaaaaaa.com?param="+0, crossDomain: true, dataType: "jsonp", success: function (response) { data =...

Set ForeignKey value from url parameter in Django's CreateView

django,dry,django-class-based-views
class Event(models.Model): ... class Question(models.Model): event = models.ForeignKey(Event) And I have url pattern like /events/(?P<event_id>\d+)/question/add/$ bound to QuestionCreateView QuestionCreateView(CreateView): model = Question form_class = QuestionForm def form_valid(self, form): form.instance.event = [???] return super(QuestionCreateView, self).form_valid(form) What I'd like to get: throw a 404 error if user requests invalid event_id like /events/9999999/objects/add/...

DRYing up resolve parameter in $routeProvider

javascript,angularjs,dry,route-provider
What is the "Angular" way in DRYing up the resolve parameter for the paths, "/A" and "/B"? In my $routeProvider, I call for the exact same resolve function for those scenarios and don't know the best way of avoiding duplicating code in the AngularJS framework. var app = angular.module("myProject", []);...

jQuery Optimization - Dry

javascript,jquery,dry
I've this simple situation: $("#check-in").dateDropper({ years_multiple: "10", format: "d-m-Y", minYear: "2015", maxYear: "2016", lang: "pt", animation: "bounce", placeholder: "Dia da entrada." }); $("#check-out").dateDropper({ years_multiple: "10", format: "d-m-Y", minYear: "2015", maxYear: "2016", lang: "pt", animation: "bounce", placeholder: "Dia da saída." }); The only difference is placeholder: "...". How can I optimize...

Duplicate commands in different ggplot2 plots

r,ggplot2,dry
This seems like an issue many people would face, along the lines of the Don't Repeat Yourself (DRY) principle. I couldn't find the answer anywhere, perhaps I've been searching for the wrong terms, which means my question title probably isn't very good. If people have better suggestions of how to...

Generic repository in Java

java,android,generics,dry
Let's say I have this class: public class PhotoRepository { private PhotoDao db; PhotoRepository(PhotoDao dao) { db = dao; } public void save(List<Photo> photos) { db.insertOrReplaceInTx(photos); } public List<Photo> all() { return db.loadAll(); } public Photo get(Long id) { return db.load(id); } } Since I have more kind of entities,...

DRY-ing up python instance-based type check

python,dry
I have code that looks like this: def transform_incoming_json_item(item, things=[]): if isinstance(item, list): for thing in item: things.append(process_thing(thing)) elif isinstance(item, dict): things.append(process_thing(item)) return things Is there a more pythonic way of doing this while making only a single call to process_thing (while preserving the type check and the two cases,...

Refactoring repetitive code -js

javascript,refactoring,dry
I have this really long function that sets all the variable positions. Is it better to leave it like this or try to refactor it? If I refactor it the only way I can think of is to do something like: function getPosition(name, id){ var name+"Box" = id.getBoundingClientRect(); var name+"Top"...

DRY controller specs with RSpec: repeated expect

ruby-on-rails,ruby,rspec,dry
I have a lot of conditions and the same expectations in my controller spec: if condition 1 - expect(reponse).to redirect_to same_url if condition 2 - expect(reponse).to redirect_to same_url if condition 3 - expect(reponse).to redirect_to same_url RSpec's DRY rules suggests using "context" instead of "if condition". Ok, there is my controller...

DRY up CSS - multiple parents to one child

css,dry
I have several hierarchies separately listed out below where first selector is the parent div, second is the image item within the div. But could I combine these somehow? .outdoors .how-to-image { cursor: pointer; } .snowsports .how-to-image { cursor: pointer; } .stripe .how-to-image { cursor: pointer; } .twilio .how-to-image {...

respecting the DRY principle for variable containing the class name

java,dry
How do you set variables which contain the class name, like TAG in android.util.Log, while respecting Dont-Repeat-Yourself? These are some possibilities: In Google code, it is often used like public class Classname { public final String TAG = "Classname"; which repeats the classname and was not refactor-renamed correctly in AndroidStudio...